Skip to main content
 首页 » 编程设计

python之反元音程序问题

2025年05月04日12tuyile006

def anti_vowel(text): 
    new = '' 
    for char in text: 
        if char in "aeiou" or char in "AEIOU": 
            ala = text.replace(char, '') 
    new = new + ala 
    return new 
print anti_vowel("Hey look Words!") 

它返回“Hey lk Wrds!”这意味着该函数以某种方式完全忽略了“e”。

请您参考如下方法:

def anti_vowel(text): 
    new = '' 
    for char in text: 
        if char in "aeiou" or char in "AEIOU": 
            ala = text.replace(char, '') 

让我们停在这里看看会发生什么:

对于消息中的每个字符,如果该字符是元音字母,您将复制一份删除那个元音字母 的原始文本。然后你将它分配给 ala...但是?

    new = new + ala 
    return new 

缩进意味着 new = new + ala 只运行一次 - 在你的 for 循环结束后。在您的示例数据“Hey look Words!”中,您看到的最后一个元音是“o”,因此 ala 包含一个没有“o”的字符串(但所有其他元音保持不变):

print anti_vowel("Hey look Words!")   # => "Hey lk Wrds!" 
print anti_vowel("aeiouAEIOU!")       # => "aeiouAEIO!" 

(您的测试字符串只有两个元音字符,'e' 和 'o',这意味着您看不出“为什么没有删除 e?”和“为什么 只有 o 被移除了?”,这本来可以更明显地指示问题!)

直接修复你的代码看起来像

def anti_vowel(text): 
    result = text 
    for char in text: 
        if char in "aeiouAEIOU": 
            result = result.replace(char, '') 
    return result 

但更 Pythonic 的方法是:

# a set allows very fast look-ups 
VOWELS = set("aeiouAEIOU") 
 
def no_vowels(s): 
    # keep every character that is not a vowel 
    return "".join(ch for ch in s if ch not in VOWELS) 
 
print(no_vowels("Look Ma, no vowels!"))  # => "Lk M, n vwls!"