DanZimmerman
DanZimmerman

Reputation: 1716

python - replace string with condition yields weird result

I wrote a function that replace the letter if the letter is the same as the next letter in the string:

word = 'abcdeefghiijkl'

def replace_letter(word):
    for i in range(len(word)-1):
        if word[i] == word[i+1]:
            word = word.replace(word[i],'7')
    return word

replace_letter(word)

This should give me 'abcd7efgh7ijkl', but I got 'abcd77fgh77jkl'. Once the letter is the same with the next one both are replaced with '7'.

Why?

Upvotes: 1

Views: 82

Answers (2)

TommyJiang
TommyJiang

Reputation: 1

the answer above has a little bug for example: when your word = 'ebcdeefghiijkl' the result of replace_letter(word) will be '7abcdeefgh7ijkl' you can try this:

def replace_letter(word):
    result=[]
    for i in range(len(word)):
        if i!=len(word)-1 and word[i] == word[i+1]:
            result.append('7')
        else:
            result.append(word[i])
    return ''.join(result)

Upvotes: 0

Simeon Visser
Simeon Visser

Reputation: 122376

You should use:

word = word.replace(word[i],'7', 1)

to indicate that you want to make one character replacement. Calling replace() without indicating how many replacements you wish to make will replace any occurrence of the character "e" (as found at word[i]) by "7".

Upvotes: 4

Related Questions