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

标签 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

最佳答案

那是因为您正在设置 newstring到循环的每次迭代中的不同字符串输出 newstring = string.replace("")您需要设置newstring到替换的字符串,然后在 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))
输出:
Original string = stack overflow
String with vowels removed = stck vrflw

关于python - 为什么我的函数部分地做它应该做的事情?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64180683/

相关文章:

python - 根据最后一列累积 NumPy 数组的行

python-3.x - 为什么 cv2.addweighted() 给出一个错误,即操作既不是 'array op array' ,也不是 'array op scalar' ,也不是 ' scalar op array' ?

python - 为什么我在这段 Python 代码上遇到断言错误?

python-3.x - wxPython TreeCtrl 非常慢,有数百万个节点(在多选树控件上)

Mac OSX 中的 Python ctags 子进程调用

python - Pandas 条形图中的自定义图例 (matplotlib)

python-3.x - 在用户定义的函数中通过 Sympy 求解线性微分方程组

python - 如何更改数组中元素的索引

python - 类型错误:使用 %s 时格式字符串的参数不足

python - 有没有办法优化矩阵与一组样本的比较?