为什么我的函数部分地做它应该做的事情?

hel*_*ack 5 python python-3.x

所以我正在尝试编写一个 Python 3 函数来接受一个字符串,删除元音并在没有元音的情况下返回它。我写了下面的代码,但它似乎只去掉了部分元音,而保留了一些未受影响。

def remove_vowels(string):
    vowels = ['a','e','i','o','u']
    newstring = ""

    for letter in string:
        if letter in vowels:
            newstring = string.replace(letter,””)
        else:
             pass

    return newstring
Run Code Online (Sandbox Code Playgroud)

小智 6

那是因为您在newstring循环的每次迭代中都设置了不同的字符串输出newstring = string.replace("")

您需要设置newstring为替换的字符串,然后运行 ​​replace on 的下一次迭代newstring。像这样:

def remove_vowels(string):
    vowels = ['a','e','i','o','u']
    newstring = string

    for letter in newstring:
        if letter in vowels:
            newstring = newstring.replace(letter , "")

    return newstring

string = "stack overflow"
print("Original string = ", string)
print("String with vowels removed = ", remove_vowels(string))
Run Code Online (Sandbox Code Playgroud)

输出:

Original string = stack overflow
String with vowels removed = stck vrflw
Run Code Online (Sandbox Code Playgroud)


Odd*_*ity 6

带有以下输入的原始 python 代码

print(remove_vowels("The quick brown fox jumps over the lazy dog"))
Run Code Online (Sandbox Code Playgroud)

返回“快速 brwn fx 跳过懒惰的 dg”

这只删除“o”元音的原因是因为您遍历每个元音并将新字符串更新为传递的字符串减去当前的元音。因此,例如,第一次通过您的 for 循环时,您的“newstring”变量将是:

The quick brown fox jumps over the lzy dog
Run Code Online (Sandbox Code Playgroud)

然后下一次迭代你的“newstring”变量将被设置为

Th quick brown fox jumps ovr th lazy dog
Run Code Online (Sandbox Code Playgroud)

等等等等。我的示例只删除 o 的原因是因为没有要替换的 U,因此永远不会调用字符串替换方法,而在没有 o 的情况下保留“newstring”变量。

要解决这个问题,您只需完全删除 newstring 并更新原始字符串,因为这是它自己的变量,这在技术上可以正常工作。

虽然这可以很容易地压缩和重构以获得更好的性能,因为您实际上根本不需要遍历您的字符串(您也不需要任何类型的新字符串,因为传递的字符串是您可以更新的自己的变量)因为pythons“String.replace”将替换所提供子字符串的所有出现并返回结果字符串(如果您没有提供最大出现次数)。

下面的代码有效

def remove_vowels(string):
    vowels = 'aeiou'
    for vowel in vowels: string = string.replace(vowel,'')
    return string

print(remove_vowels("The quick brown fox jumps over the lazy dog"))
Run Code Online (Sandbox Code Playgroud)

并返回“Th qck brwn fx jmps vr th lzy dg”