String Replace Vowels In Python?
Solution 1:
Here is a version using a list instead of a generator:
defremoveVowels(word):
letters = [] # make an empty list to hold the non-vowelsfor char in word: # for each character in the wordif char.lower() notin'aeiou': # if the letter is not a vowel
letters.append(char) # add it to the list of non-vowelsreturn''.join(letters) # join the list of non-vowels together into a string
You could also write it just as
''.join(charforcharin word ifchar.lower() notin'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(charforcharin word if charnotinset('aeiouAEIOU'))
Solution 2:
re.sub('[aeiou]', '', 'Banana', flags=re.I)
Solution 3:
Using bytes.translate() method:
defremoveVowels(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() notin 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?"