String Replace Vowels In Python?
Solution 1:
Here is a version using a list instead of a generator:
def removeVowels(word):
letters = [] # make an empty list to hold the non-vowels
for char in word: # for each character in the word
if char.lower() not in 'aeiou': # if the letter is not a vowel
letters.append(char) # add it to the list of non-vowels
return ''.join(letters) # join the list of non-vowels together into a string
You could also write it just as
''.join(char for char in word if char.lower() not in 'aeiou')
Which does the same thing, except finding the non-vowels one at a time as join
needs them to make the new string, instead of adding them to a list then joining them at the end.
If you wanted to speed it up, making the string of values a set
makes looking up each character in them faster, and having the upper case letters too means you don't have to convert each character to lowercase.
''.join(char for char in word if char not in set('aeiouAEIOU'))
Solution 2:
re.sub('[aeiou]', '', 'Banana', flags=re.I)
Solution 3:
Using bytes.translate() method:
def removeVowels(word, vowels=b'aeiouAEIOU'):
return word.translate(None, vowels)
Example:
>>> removeVowels('apple')
'ppl'
>>> removeVowels('Apple')
'ppl'
>>> removeVowels('Banana')
'Bnn'
Solution 4:
@katrielalex solution can be also simplified into a generator expression:
def removeVowels(word):
VOWELS = ('a', 'e', 'i', 'o', 'u')
return ''.join(X for X in word if X.lower() not in VOWELS)
Solution 5:
Since all the other answers completely rewrite the code I figured you'd like one with your code, only slightly modified. Also, I kept it simple, since you're a beginner.
A side note: because you reassign res
to word
in every for loop, you'll only get the last vowel replaced. Instead replace the vowels directly in word
def removeVowels(word):
vowels = ('a', 'e', 'i', 'o', 'u')
for c in word:
if c.lower() in vowels:
word = word.replace(c,"")
return word
Explanation: I just changed if c in vowels:
to if c.lower() in vowels:
.lower()
convert a string to lowercase. So it converted each letter to lowercase, then checked the letter to see if it was in the tuple of vowels, and then replaced it if it was.
The other answers are all good ones, so you should check out the methods they use if you don't know them yet.
Hope this helps!
Post a Comment for "String Replace Vowels In Python?"