1

I am attempting to write a method that replaces every occurrence of a letter after the first as a "*" instead of the letter. Examples: "babble" yields "ba**le" "that" yields "tha*"

My code seems to be having an issue with the replace function while looping and I can't quite figure out why.

def fix_start(s):
    if len(s) < 2:
        s = "" 
    else:
        for i in s:
            if i == s[0]:
                if s[0]:
                    continue
                s.replace(s[i], "*")
                i += i
    print(s)
3
  • replace doesn't replace in place, it returns a new string. I didn't check the rest of your code, but you need s = s.replace(...) Commented Sep 24, 2019 at 17:20
  • That didn't seem to do the trick. Commented Sep 24, 2019 at 17:23
  • As Isaid, I didn't check the rest of your code, so there are probably other problems in it. Commented Sep 24, 2019 at 17:25

1 Answer 1

1

The str.replace method returns a copy of the original string with all occurrences of the given substring replaced with the given new string, so you can simply slice the input string from the second character and replace all occurrences of the first character with '*', and concatenate it after the first character of the orignal string:

def fix_start(s):
    return s[0] + s[1:].replace(s[0], '*')

so that fix_start('babble') returns: 'ba**le'

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.