How to replace a character in a string with another character in Python?

I want to replace every character that is not an "i" in the string "aeiou" with "!"

I wrote:

def changeWord(word): for letter in word: if letter != "i": word.replace(letter,"!") return word 

It just returns the original. How can I return "!! i !!"?

+4
source share
5 answers

Strings in Python are immutable, so you cannot change them. Check out the str.replace documentation :

Returns a copy of the string with all occurrences of the substring old, replaced by the new one. If the optional argument count is provided, only the first counter instances are replaced.

To make it work, do the following:

 def changeWord(word): for letter in word: if letter != "i": word = word.replace(letter,"!") return word 
+5
source

Regular expressions are quite effective for this kind of thing. This replaces any character that is not an "i" with a "!"

 import re str = "aieou" print re.sub('[^i]', '!', str) 

returns:

 !!i!! 
+3
source

something like this with split() and join() :

 In [4]: strs="aeiou" In [5]: "i".join("!"*len(x) for x in strs.split("i")) Out[5]: '!!i!!' 
+2
source

Try this as a single line:

 def changeWord(word): return ''.join(c if c == 'i' else '!' for c in word) 

The answer can be briefly expressed using a generator, in this case there is no need to use regular expressions or loops.

+2
source

No one seems to like str.translate :

 In [25]: chars = "!"*105 + 'i' + "!"*150 In [26]: 'aeiou'.translate(chars) Out[26]: '!!i!!' 

Hope this helps

+2
source

Source: https://habr.com/ru/post/1446722/


All Articles