简体   繁体   中英

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?

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).

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM