.replace, anti_vowel


#1

Strings and Console Output

Hello, I wonder why my code is only partially working.

def anti_vowel(text):
for char in text:
if char in “aeioAEIOU”:
string = text.replace(char, “”)
#print char
return string

print anti_vowel(“Hey look Words”)

I get back Hey lk Wrds.
when I print the char it prints e,o,o,o but it doesn’t replace the e.
also if I give it “Hey Look” I get back Hy Lk.
I also tried to give it a max value replace(char, “”, 10), it didn’t make any difference.
I can think of other ways to write this function, for example with append to a new string instead of replacing but I would really like to know why its only partially working.

Thanks!


#2
string = text.replace(char, “”)

In each time this line executes, string is a snapshot of text. text itself is not changed. To effect an actual change, assign it back to itself.

text = text.replace(...)

It’s never a good idea to mutate the object we are iterating over. Better to iterate over a copy of the object and mutate the original, or in this case, iterate over only the vowel string, and mutate the text.


#3

Thanks! I read somewhere that you can not change the original string with replace(), thats the reason I used the variable string in the first place but that was obviously wrong.


#4

Strings are immutable, but the replace method depends upon a new assignment, which is why we assign back on to the original variable. The string is not changed, but replaced with the mutated string.

for letter in 'aeiouAEIOU':
    text =  text.replace(letter, '')

#5

now its all clear. Thanks again!


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.