Skip to content Skip to sidebar Skip to footer

Python: .replace Doesn't Work In Method Function?

When I run this: def Replace(word): word.replace('o', 'x') return word print Replace('word') print 'word'.replace('o', 'x') I get this: word wxrd I am just starting to u

Solution 1:

.replace()doesn't replace in place - it returns a new string which you should return:

def Replace(word):
    new_word = word.replace('o', 'x')
    return new_word

Solution 2:

You discard the result of str.replace(), and return the original word. Try returning the result instead.

Solution 3:

Just do:

defReplace(word):
a = word.replace('o', 'x')
return a

print Replace('word')
print'word'.replace('o', 'x')

Then you should get:

wxrd
wxrd

Post a Comment for "Python: .replace Doesn't Work In Method Function?"