Skip to main content
 首页 » 编程设计

python之从字符串中,如何只返回不以元音开头的单词

2025年05月04日29bjzhanghao

我有一个字符串“狗是好宠物”

我希望能够只返回以辅音开头的单词。 ["dog", "good", "pet"] 作为列表

def consonant_first(newstr): 
    for char in newstr.split(): 
        if char[0] in newstr.split() ==  vowels1: 
            return newstr.split()  
print(newstr) 

请您参考如下方法:

只需测试列表理解中的第一个字母:

s = "A dog is a good pet" 
 
def consonant_first(newstr): 
    return [word for word in s.split() if  word[0].lower() not in 'aeiou'] 
 
print(consonant_first(s)) 

确保针对所有情况进行测试,以便捕获 A。

结果:

['dog', 'good', 'pet']