How do I replace a character in a string with another character in Python?
Strings in Python are immutable, so you cannot change them in place. Check out the documentation of str.replace:
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
So to make it work, do this:
def changeWord(word):
for letter in word:
if letter != "i":
word = word.replace(letter,"!")
return word
Regular expressions are pretty powerful for this kind of thing. This replaces any character that isn't an "i" with "!"
import re
str = "aieou"
print re.sub('[^i]', '!', str)
returns:
!!i!!
something like this using split()
and join()
:
In [4]: strs="aeiou"
In [5]: "i".join("!"*len(x) for x in strs.split("i"))
Out[5]: '!!i!!'