So this code is in a tutorial and I couldn’t figure out why it it had both newStr and string so I tried the code in a simplified way (shown following below) and it still works. Is there a benefit to both variables, I found it confusing. Also in my version the line:
for c in string.lower ()
I have as:
for c in string
…and it still works- why is that?
def remove_vowels (newStr,string):
vowels =("a", "e", "i", "o", "u")
for c in string.lower():
if c in vowels:
newStr =newStr.replace(c, " ")
return newStr
print ("Enter x to exit")
string =input ("Enter string to remove vowels: ")
if string == "x":
exit()
else:
newStr=string
print("removing vowels")
newStr =remove_vowels (newStr,string)
print('The new string is: ', newStr)
My version:
def remove_vowels (string):
vowels =("a", "e", "i", "o", "u")
for c in string:
if c in vowels:
string =string.replace(c, " ")
return string
print ("Enter x to exit")
string =input ("Enter string to remove vowels: ")
if string == "x":
exit()
else:
print("removing vowels")
string =remove_vowels (string)
print('The new string is: ', string)
I would guess that you have only entered a lower case string, eg “a dog”
versus something with a mix eg “A dog.”.
The purpose of iterating over string.lower() is so that all the
letters are lower case so that you can look it up in your vowels, which
are all lower case. If you look at:
"A" in ("a", "e", "i", "o", "u")
you should get False.
BTW, your remove_vowels() function is better than that in the
tutorial. No need to pass in newStr, indeed.
There is one slightly weird aspect which works fine here but is not a great habit to get into: iterating over string while modifying it.
As it happens, the for loop captures the value at the time and doesn’t update it as the vowels are removed. With a different sequence (e.g. a list) and a different operation (e.g. swapping pairs of letters around) modifying it in-place can cause sneaky bugs.
If we add some print statements we can see it happening:
Enter string to remove vowels: ooahaha
removing vowels
found 'o' in ooahaha, replacing it
found 'o' in ahaha, replacing it
found 'a' in ahaha, replacing it
found 'a' in h h , replacing it
found 'a' in h h , replacing it
The new string is: h h
In the second iteration the o is gone from string but the for loop still sees it. Sneaky!
This also shows another thing that can be improved: don’t loop over the string, loop over the vowels! We only need to replace them once each.
Just as an observation - this not removing vowels, it’s replacing vowels with space (vowels → vwls vs v w ls; those spaces weren’t present in original string)