如果单词有辅音,则使用python函数删除元音

时间:2018-09-24 07:41:19

标签: python string

规则1:如果一个单词只有元音,则按原样保留该单词
规则2:如果单词有辅音,则仅保留这些辅音

但是我无法根据上述规则输出我的信息。

输出应为:

MSD sys i lv crckt nd tnns t

但我的输出是:

MSD sys lv crckt nd tnns t

代码:

def encrypt(message):
    word_list=message.split(" ")
    final_list=[]
    consonant_word=""
    vowel_list=("a","e","i","o","u","A","E","I","O","U")
    for word in word_list:
            for letter in word:
                if letter in vowel_list:
                    message=message.replace(letter,"")      
    return message

message="MSD says i love cricket and tennis too"            
print(encrypt(message))

2 个答案:

答案 0 :(得分:1)

以下将起作用:

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'

答案 1 :(得分:0)

您的问题是您要替换遇到的任何元音-因此“ i”将被删除。在从单词中删除元音之前,您需要检查单词是否有辅音。您可以这样做:

if any(

如果单词中有任何非元音(即辅音),则[letter for letter in word if letter not in vowels] 行将为true。然后找到所有非元音字母:

hotkey()