替换方法问题

时间:2017-01-05 23:43:40

标签: python string for-loop replace

我有这个代码似乎工作得很好,只是它留下了一个“e”!该代码旨在循环遍历给定的字符串,删除元音,然后返回新的反元音字符串。

def anti_vowel(text):
    anti_v = ''
    for c in text:
        if c in "aeiouAEIOU":
            anti_v = text.replace(c, '')
        else:
            anti_v.join(c)
    return anti_v

测试代码:

anti_vowel("Hey look Words!")

这将返回“Hey lk Wrds!”

是什么给出的?谢谢!

3 个答案:

答案 0 :(得分:1)

您可以使用理解来加入字符串中不是元音的所有字符:

def anti_vowel(text):
    return ''.join(c for c in text if c not in 'aeiouAEIOU')

答案 1 :(得分:1)

我认为问题在于你将值存储在anti_v中,但是每次循环时,你都会用text.replace(c,''的值)替换anti_v的值。 ),但文本变量不会改变。 例如,如果文字是' aae'

c = 'a' ---> anti_v = 'aae'.replace('a', '') --> anti_v='e'
c = 'a' ---> anti_v = 'aae'.replace('a', '') --> anti_v='e'
c = 'e' ---> anti_v = 'aae'.replace('e', '') --> anti_v='aa'

因此,在这种情况下,anti_vowel的回归将是' aa'而不是空字符串。

解决这个问题的一种方法是做@VHarisop所建议的。

此外,您可以查看this主题,查看其他选项以删除字符串上的元音。

答案 2 :(得分:0)

每次运行循环时,都会对text参数进行替换。 但是当你做替换时,原始值不会改变。因此,下次更换时,您将在原始字符串上执行此操作。例如:

print(text.replace('e', '')) # Hy hy look txt!
print(text) # Hey hey look text!

它似乎适用于其他元音,因为你的其他人将c加入anti_v。

你根本不需要别人。只需将anti_v设置为等于text并在anti_v上执行替换。这将解决您的问题。

def anti_vowel(text):
    anti_v = text
    for c in text:
        if c in "aeiouAEIOU":
            anti_v = anti_v.replace(c, '')

    return anti_v

或者只是一起删除anti_v变量并使用text:

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

    return text