0

I'm trying to remove all the vowels from a string, using a function that is passed an argument called "text". I'm not sure if this is the most efficient way to code this, but it's all I could come up with. I'm not sure how to tell the function to check if "text" has any of the characters from the "vowels" list, and if so, to remove it. I thought replacing it with a space would do in the .replace() function would do the trick, but apparently not. The code is supposed to remove lower AND uppercase vowels, so I'm not sure if making them all lowercase is even acceptable. Thanks in advance.

def anti_vowel(text): #Function Definition

    vowels = ['a','e','i','o','u'] #Letters to filter out
    text = text.lower() #Convert string to lower case

    for char in range(0,len(text)):
        if char == vowels[0,4]:
            text = text.replace(char,"")

        else:
            return text
user590028
  • 11,364
  • 3
  • 40
  • 57
Jason T. Eyerly
  • 183
  • 1
  • 6
  • 18

4 Answers4

6

Pretty simple using str.translate() (https://docs.python.org/2.7/library/stdtypes.html#str.translate)

return text.translate(None, 'aeiouAEIOU')
user590028
  • 11,364
  • 3
  • 40
  • 57
0

Python's Replace has you specify a substring to replace, not a position in the string. What you would want to do instead is

for char in range(0,5):
  text = text.replace(vowels[char],"")
return text

UPDATED BASED ON COMMENT: or you could do

for char in vowels:
   text = text.replace(char,"");
return text;
Rolyataylor2
  • 201
  • 1
  • 5
0

Use the sub() function (https://docs.python.org/2/library/re.html#re.sub):

re.sub('[aeiou]', '', text)
Slippery Pete
  • 3,051
  • 1
  • 13
  • 15
0

Change your function to loop over the vowels list like this:

def anti_vowel(text): #Function Definition

    vowels = ['a','e','i','o','u'] #Letters to filter out
    text = text.lower() #Convert string to lower case

    for vowel in vowels:
        text = text.replace(vowel,"")
    return text

This simply iterates over the vowels and replaces all occurrences of each vowel.

user2963623
  • 2,267
  • 1
  • 14
  • 25