newbie newbie - 1 year ago 216
Python Question

string replace vowels in python?


>>> removeVowels('apple')
>>> removeVowels('Apple')
>>> removeVowels('Banana')

CODE (Beginner):

def removeVowels(word):
vowels = ('a', 'e', 'i', 'o', 'u')
for c in word:
if c in vowels:
res = word.replace(c,"")
return res

How I do both lowercase and upercase?

agf agf
Answer Source

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'))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download