python函数,用于在单词有辅音时删除元音

python函数,用于在单词有辅音时删除元音,python,string,Python,String,规则1:如果一个单词只有元音,那么就保持原样 规则2:如果一个单词有一个辅音,那么只保留那些辅音 但我无法按照上述规则输出 输出应为: MSD sys i lv crckt nd tnns t 但我的输出是: MSD sys lv crckt nd tnns t 代码: 以下工作将起作用: def encrypt(message): vowel_set = set("aeiouAEIOU") # set has better contains-check final_lis

规则1:如果一个单词只有元音,那么就保持原样
规则2:如果一个单词有一个辅音,那么只保留那些辅音

但我无法按照上述规则输出

输出应为:

MSD sys i lv crckt nd tnns t
但我的输出是:

MSD sys lv crckt nd tnns t
代码:


以下工作将起作用:

def encrypt(message):
    vowel_set = set("aeiouAEIOU")  # set has better contains-check
    final_list = []
    for word in message.split(" "):
        if all(c in vowel_set for c in word):  # all vowel word
            final_list.append(word)  # unchanged
        else:
            # build word of only consonants
            final_list.append("".join(c for c in word if c not in vowel_set))
    return " ".join(final_list)

>>> encrypt('MESUD says i love cricket and tennis too')
'MSD sys i lv crckt nd tnns t'

你的问题是你正在替换你遇到的任何元音,所以“i”将被删除。在去掉元音之前,你需要检查一个单词是否有辅音。您可以这样做:

def encrypt(message):
    words = message.split(" ")
    vowels=("aeiouAEIOU")
    encrypted_words = []
    for word in words:
        if any(letter not in vowels for letter in word):
            word = ''.join([letter for letter in word if letter not in vowels])
        encrypted_words.append(word)
    return " ".join(encrypted_words)
如果单词中有任何非元音字母(即辅音),则
if any(
行为true)。然后查找所有非元音字母:

[letter for letter in word if letter not in vowels]

@Aran Fey我已经编辑了代码。很抱歉给您带来不便,您不需要使用拆分()就像邮件中的字母一样使用它:谢谢你@schwobaseggl我花了两天时间试图解决这个错误。最后你在一秒钟内解决了。再次感谢。是的,我读过了。你能检查我下面给出的答案吗?有什么问题吗?不知道我不是专家,对python@abhikrishnan但是你的答案和问题不一样n要求,即只包含元音的单词应保持原样。
[letter for letter in word if letter not in vowels]