反元音节目问题

时间:2014-03-21 05:07:02

标签: python

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”。

4 个答案:

答案 0 :(得分:6)

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

缩进意味着{for循环完成后new = new + ala 仅运行一次。在您的示例数据上,"嘿看单词!",您看到的最后一个元音是' o',因此ala包含一个没有' o&#的字符串39; s(但所有其他元音留下):

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

(你的测试字符串只有两个元音字符,&#39;和&#39; o&#39;,这意味着你看不出&#34之间的任何区别;为什么是e没有删除?&#34;和&#34;为什么只删除了<&em>?&#34;,这可能是问题的一个更明显的指标!)

直接修复代码看起来像

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!"

答案 1 :(得分:1)

您可以检查char是否不是元音。如果不是,则将其添加到字符串:

def anti_vowel(text):
    new = ''
    for char in text:
        if char not in "aeiouAEIOU":
            new += char
    return new

注意,最好使用

if char not in "aeiouAEIOU":

或(如@Michal评论):

 if char.lower not in "aeiou":

而不是

if char not in "aeiou" and char not in "AEIOU":

答案 2 :(得分:1)

问题是您每次都在text进行替换,而不是更新变量ala。试试这个:

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

答案 3 :(得分:0)

字符串在Python中是不可变的。因此,当您执行以下操作时,

ala = text.replace(char, '')

这会创建一个用空字符串替换char的新字符串,并将其分配给ala。但是,text的值仍然是函数anti_vowel传递的原始字符串。循环终止后,ala的值将是原始字符串,其中删除了最后一个元音的所有匹配项。你应该做的是 -

def anti_vowel(text):
    for char in text:
        if char in "aeiouAEIOU":
            # update text after replacing all instances of the vowel
            # char in text with the empty string
            text = text.replace(char, '')
    return text

您也可以考虑使用字符串方法translate

def anti_vowel(text):
    vowels = "aeiouAEIOU"
    return text.translate(None, vowels)