简体   繁体   中英

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.replace(letter,"!")
    return word

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

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

Try this, as a one-liner:

def changeWord(word):
    return ''.join(c if c == '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.

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

Generally in python string are immutable that means it can't be changed after its creation. So we have to convert string into mutable and that can be possible using list as it is mutable.

string="Love"

editable = list(string)
editable[2]='s'
string=''.join(editable)

output:Lose

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM