Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 341
Aei Avatar asked Nov 18 '12 03:11

Aei


People also ask

How do you replace a character in a string with another character?

The Java string replace() method will replace a character or substring with another character or string. The syntax for the replace() method is string_name. replace(old_string, new_string) with old_string being the substring you'd like to replace and new_string being the substring that will take its place.

How do you replace part of a string in Python?

In Python, the . replace() method and the re. sub() function are often used to clean up text by removing strings or substrings or replacing them.

How do you switch characters in a string in Python?

strs[(strs. index(i) + shift) % 26] : line above means find the index of the character i in strs and then add the shift value to it. Now, on the final value(index+shift) apply %26 to the get the shifted index. This shifted index when passed to strs[new_index] yields the desired shifted character.

What does replace () do in Python?

The replace() method replaces a specified phrase with another specified phrase. Note: All occurrences of the specified phrase will be replaced, if nothing else is specified.


1 Answers

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
like image 76
JoelWilson Avatar answered Oct 02 '22 10:10

JoelWilson