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!!"?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With