我想返回一个单词列表,其中包含一个不考虑大小写的字母。说如果我有sentence = "Anyone who has never made a mistake has never tried anything new",那么f(sentence, a)会回来['Anyone', 'has', 'made', 'a', 'mistake', 'has', 'anything']这就是我所拥有的import re def f(string, match): string_list = string.split() match_list = [] for word in string_list: if match in word: match_list.append(word) return match_list
3 回答
蓝山帝景
TA贡献1843条经验 获得超7个赞
你不需要re
。使用str.casefold
:
[w for w in sentence.split() if "a" in w.casefold()]
输出:
['Anyone', 'has', 'made', 'a', 'mistake', 'has', 'anything']
白衣染霜花
TA贡献1796条经验 获得超10个赞
这是另一个变体:
sentence = 'Anyone who has never made a mistake has never tried anything new'
def f (string, match) :
match_list = []
for word in string.split () :
if match in word.lower ():
match_list.append (word)
return match_list
print (f (sentence, 'a'))
慕哥6287543
TA贡献1831条经验 获得超10个赞
如果没有标点符号,您可以使用字符串拆分。
match_list = [s for s in sentence.split(' ') if 'a' in s.lower()]
添加回答
举报
0/150
提交
取消