Skip to content Skip to sidebar Skip to footer

How Do I Replace A Character In A String With Another Character In Python?

I want to replace every character that isn't 'i' in the string 'aeiou' with a '!' I wrote: def changeWord(word): for letter in word: if letter != 'i': word.

Solution 1:

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

Solution 2:

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!!

Solution 3:

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!!'

Solution 4:

Try this, as a one-liner:

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

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

Solution 5:

Nobody seems to give any love to str.translate:

In [25]: chars = "!"*105 + 'i' + "!"*150

In [26]: 'aeiou'.translate(chars)
Out[26]: '!!i!!'

Hope this helps

Post a Comment for "How Do I Replace A Character In A String With Another Character In Python?"