python - def anti_vowel - Codecademy (python)

标签 python string function

我在创建反元音定义方面有点困难:

Define a function called anti_vowel that takes one string, text, as input and returns the text with all of the vowels removed

这是我的尝试:

def anti_vowel(text):
    vowels=["a","A","e","E","i","I","o","O","u","U"]
    text_input=[""]
    for char in text:
        text_input.append(char)
    av = [char for char in text_input if char not in vowels]
    return av

我的代码将输入作为单独的字符返回。

这是我得到的错误:

Oops, try again. Your function fails on anti_vowel("Hey look Words!"). It returns "['', 'H', 'y', ' ', 'l', 'k', ' ', 'W', 'r', 'd', 's', '!']" when it should return "Hy lk Wrds!". 

有人可以给我指出正确的方向吗?

最佳答案

考虑:

>>> tgt='This is some text with vowels'
>>> vowels='aeiou'
>>> ''.join(e for e in tgt if e.lower() not in vowels)
'Ths s sm txt wth vwls'

或者,正如评论中指出的,在 join is better 中使用实际的列表理解:

>>> ''.join([e for e in tgt if e.lower() not in vowels])
'Ths s sm txt wth vwls'

关于python - def anti_vowel - Codecademy (python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25028807/

相关文章:

python - 在 Altair 中保留上一层的工具提示

javascript - 在javascript中将字符串转换为对象

你能假设类型转换指针是安全的吗?

javascript - jQuery:在执行 toggleClass 之后执行一个函数

python - vim 的 Youcompleteme 插件无法为来自 errno.h 的错误代码提供补全

python - Tensorflow 抛出分布式函数错误

python - 如何在 python 中跳出 try 循环?

C# 4.0 如何获取给定字符串的 64 位哈希码

python - 在 Python 中扩展字符串中的所有出现

python - 为什么我不能在用户定义函数中重写列表?