Python 替换方法问题

Python 替换方法问题,python,string,for-loop,replace,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 测试代

我有这个代码,它似乎工作得很好,除了它省略了一个“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!")
这将返回“嘿,lk Wrds!”


有什么好处?谢谢

每次运行循环时,都会替换文本参数。 但是,当您进行替换时,原始值不会改变。因此,下次替换时,您是在原始字符串上进行替换。例如:

print(text.replace('e', '')) # Hy hy look txt!
print(text) # Hey hey look text!
它似乎适用于其他元音,因为你的else将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变量并使用文本:

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

    return text

您可以使用理解来连接字符串中所有非元音的字符:

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

我认为问题在于,您将值存储在anti_v中,但每次运行循环时,您都将anti_v的值替换为text.replace(c“”),但text变量不会更改。 例如,如果文本是“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'
因此,在这种情况下,反_元音的返回将是“aa”,而不是空字符串

解决这个问题的一种方法是按照@VHarisop的建议去做

此外,您还可以查看线程以查看删除字符串上元音的其他选项。

反v.join(c)
的功能与您所想的完全不同<代码>文本。替换(c),也不会替换
'e'
'o'
或任何东西的特定实例;它将替换所有实例。每次执行另一个替换时,您也会丢弃旧的替换。