[英]Return a list of words that contain a letter
我想返回一個包含字母的單詞列表,不考慮大小寫。 假設我有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
你不需要re
。 使用str.casefold
:
[w for w in sentence.split() if "a" in w.casefold()]
輸出:
['Anyone', 'has', 'made', 'a', 'mistake', 'has', 'anything']
如果沒有標點符號,您可以使用字符串拆分。
match_list = [s for s in sentence.split(' ') if 'a' in s.lower()]
這是另一個變化:
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'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.