我想返回一個單詞列表,其中包含一個不考慮大小寫的字母。說如果我有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
提交
取消