saadhq20
saadhq20

Reputation: 1

Deleting vowels in string in python:

The code:

def anti_vowel(text):
    string1 = list(text)
    for i in string1:
        if i=='A'or i=='a' or i=='E'or i=='e'or i=='O'or i=='o' or \
        i=='I'or i=='i' or i=='U' or i=='u':
            del(string1[string1.index(i)])
    string2 = ''.join(string1)
    return string2

Gives an error:

Your function fails on anti_vowel("Hey look Words!").

It returns "Hy lk Words!" when it should return "Hy lk Wrds!".

I don't know how to delete that "o" in "words". Can you tell me what's wrong?

Upvotes: 0

Views: 282

Answers (3)

Kenneth E. Bellock
Kenneth E. Bellock

Reputation: 1056

This looks like a good place to be using regular expressions...

import re
re_vowels = re.compile(r'[AaEeIiOoUu]')
def anti_vowel(text):
    return re_vowels.sub('', text)

Results in 'hy lk Wrds!'

But if you have to fix the code you have, try this...

def anti_vowel(text):
    string1 = list(text)
    for c in xrange(len(string1)-1,-1,-1):
        i = string1[c]
        if i=='A'or i=='a' or i=='E'or i=='e'or i=='O'or i=='o' or \
        i=='I'or i=='i' or i=='U' or i=='u':
            del(string1[c])
    string2 = ''.join(string1)
    return string2

Or...

def anti_vowel(text):
    return ''.join([c for c in text if c.lower() not in 'aeiou'])

In your code you are trying to delete something that doesn't exist anymore. If you are going to iterate through a list while deleting elements, iterate through it in reverse order (or use list comprehensions).

Upvotes: 3

Joe T. Boka
Joe T. Boka

Reputation: 6585

If you just want to remove vowels from strings this is an easy way to do it:

word = "hello world"
w = filter(lambda x: x not in 'aeiouAEIOU', word)
print w

Output:

hll wrld

Upvotes: 3

Josh Stevens
Josh Stevens

Reputation: 4221

your code is messy and not nice you can do it a easy way by setting vowels and comparing them to the value like below. This then will do a replace on the vowels which match in the string.

 def anti_vowel(text):
        string1 = text
        vowels = ('a', 'e', 'i', 'o', 'u')
        for x in text.lower():
            if x in vowels:
                string1 = string1.replace(x,"")

        return string1

Upvotes: 0

Related Questions