Correct code to remove the vowels from a string in

2019-01-02 21:37发布

I'm pretty sure my code is correct but it doesn't seem to returning the expected output:

input anti_vowel("Hey look words") --> outputs: "Hey lk wrds".

Apparently it's not working on the 'e', can anyone explain why?

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

标签: python
13条回答
梦寄多情
2楼-- · 2019-01-02 21:44
vowels = ('a', 'e', 'i', 'o', 'u', 'A', 'I', 'E', 'O', 'U')

for char in text:

    if char in vowels:

        text = text.replace(char, '')

return text
查看更多
情到深处是孤独
3楼-- · 2019-01-02 21:47
def anti_vowel(text):
new=[]
vowels = ("aeiouAEIOU")
for i in text:
    if i not in vowels:
        new.append(i)
return ''.join(new)

i hope this helps..

查看更多
ら面具成の殇う
4楼-- · 2019-01-02 21:48

The function str.replace(old, new[, max]) don't changes c string itself (wrt to c you calls) just returns a new string which the occurrences of old have been replaced with new. So newstr just contains a string replaced by last vowel in c string that is the o and hence you are getting "Hey lk wrds" that is same as "Hey look words".replace('o', '').

I think you can simply write anti_vowel(c) as:

''.join([l for l in c if l not in vowels]);

What I am doing is iterating over string and if a letter is not a vowel then only include it into list(filters). After filtering I join back list as a string.

查看更多
笑指拈花
5楼-- · 2019-01-02 21:48

A fairly simple approach could be;

def anti_vowel(text):
    t = ''
    for c in text:
        if c in "aeiouAEIOU":
            pass
    else:  
        t += c  
    return t  
查看更多
姐姐魅力值爆表
6楼-- · 2019-01-02 21:53
def anti_vowel(text):
    t=""
    for c in text:
        for i in "ieaouIEAOU":
            if c==i:
                c=""
            else:
                c=c
        t=t+c
    return t
查看更多
孤独寂梦人
7楼-- · 2019-01-02 21:54

Try String.translate.

>>> "Hey look words".translate(None, 'aeiouAEIOU')
'Hy lk wrds'

string.translate(s, table[, deletechars])

Delete all characters from s that are in deletechars (if present), and then translate the characters using table, which must be a 256-character string giving the translation for each character value, indexed by its ordinal. If table is None, then only the character deletion step is performed.

https://docs.python.org/2/library/string.html#string.Template.substitute

Or if you're using the newfangled Python 3:

>>> table = str.maketrans(dict.fromkeys('aeiouAEIOU'))
>>> "Hey look words.translate(table)
'Hy lk wrds'
查看更多
登录 后发表回答