在Python中从字符串中删除元音的正确代码

2024-05-15 11:35:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我很确定我的代码是正确的,但它似乎没有返回预期的输出:

输入anti_vowel("Hey look words")-->;输出:"Hey lk wrds"

显然它不在'e'上工作,有人能解释为什么吗?

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

Tags: 代码ingtfordeflowerwordslook
3条回答

试试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

或者如果您使用的是新式的Python 3:

>>> table = str.maketrans(dict.fromkeys('aeiouAEIOU'))
>>> "Hey look words.translate(table)
'Hy lk wrds'

函数^{}不改变c字符串本身(wrt to c您调用的)只返回一个新字符串,旧字符串的出现已被新字符串替换。因此newstr只包含一个被c字符串中最后一个元音替换的字符串,即o,因此得到的"Hey lk wrds""Hey look words".replace('o', '')相同。

我认为您可以简单地将anti_vowel(c)写成:

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

我所做的是遍历字符串,如果一个字母不是元音,那么只将它包含在列表(过滤器)中。过滤之后,我以字符串的形式返回列表。

你为什么不用regexp呢?根据documentation的说法,类似这样的操作应该有效:

import re

def anti_vowel(s):
    result = re.sub(r'[AEIOU]', '', s, flags=re.IGNORECASE)
    return result

如果经常使用该函数,可以编译regexp并使用编译后的版本。

相关问题 更多 >