I'm trying to write a function that gets rid of the vowels in a given string, but it seems to not behave the way it should do...
def anti_vowel(text):
for c in text:
if c in "aeiouAEIOU":
no_vowel = text.replace(c, '')
return no_vowel
print(anti_vowel('Hello World')
so instead of printing
Hll Wrld
It prints
Hell Wrld
Thanks (in advance) for helping
The problem is that no_vowel only has the value of the last time that text.replace(c, '') was executed. Another issue is that no_vowel only gets a value when there is actually a vowel to remove; the code would fail on anti_vowel('vwllss'). Furthermore, you don't have to check whether a character is contained in the text before calling str.replace().
This should work:
def anti_vowel(text):
for vowel in "aeiouAEIOU":
text = text.replace(vowel, '')
return text
print(anti_vowel('Hello World'))
As others indicated, another approach would be to write code in a different way:
def anti_vowel(text):
''.join(c for c in text if c not in 'aeiouAEIOU')
Please do use a generator expression in ''.join() and not a list comprehension; such a list comprehension would allocate memory unnecessarily.
You can use string.translate() for this. For example:
def anti_vowel(text):
return text.translate(None, "aeiouAEIOU")
print(anti_vowel("hello world"))
With Python 3 the delete argument is gone, but you can still do it by mapping a character to None.
def anti_vowel_py3(text):
return text.translate({ord(i): None for i in "aeiouAEIOU"})
print(anti_vowel_py3("hello world"))
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