从 Python 中的字符串中删除元音的正确代码 [英] Correct code to remove the vowels from a string in Python

查看:76
本文介绍了从 Python 中的字符串中删除元音的正确代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很确定我的代码是正确的,但它似乎没有返回预期的输出:

I'm pretty sure my code is correct but it doesn't seem to returning the expected output:

input anti_vowel("Hey look words") --> 输出:"Hey lk wrds".

input anti_vowel("Hey look words") --> outputs: "Hey lk wrds".

显然它不适用于 'e',谁能解释一下原因?

Apparently it's not working on the 'e', can anyone explain why?

def anti_vowel(c):
    newstr = ""
    vowels = ('a', 'e', 'i', 'o', 'u')
    for x in c.lower():
        if x in vowels:
            newstr = c.replace(x, "")        
    return newstr

推荐答案

str.replace(old, new[, max]) 不要改变 c 字符串本身(wrt to c 你调用)只返回一个新字符串,旧的出现已被新替换.所以 newstr 只包含一个由 c 字符串中的最后一个元音替换的字符串,即 o,因此你得到 "Hey lk wrds""Hey look words".replace('o', '') 相同.

The function str.replace(old, new[, max]) don't changes c string itself (wrt to c you calls) just returns a new string which the occurrences of old have been replaced with new. So newstr just contains a string replaced by last vowel in c string that is the o and hence you are getting "Hey lk wrds" that is same as "Hey look words".replace('o', '').

我认为你可以简单地将 anti_vowel(c) 写成:

I think you can simply write anti_vowel(c) as:

''.join([l for l in c if l not in vowels]);

我正在做的是遍历字符串,如果一个字母不是元音,那么只将它包含在列表(过滤器)中.过滤后,我将列表作为字符串加入.

What I am doing is iterating over string and if a letter is not a vowel then only include it into list(filters). After filtering I join back list as a string.

这篇关于从 Python 中的字符串中删除元音的正确代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆