[英]Return a list of words that contain a letter
I wanna return a list of words containing a letter disregarding its case.我想返回一个包含字母的单词列表,不考虑大小写。 Say if i have
sentence = "Anyone who has never made a mistake has never tried anything new"
, then f(sentence, a)
would return假设我有
sentence = "Anyone who has never made a mistake has never tried anything new"
,那么f(sentence, a)
将返回
['Anyone', 'has', 'made', 'a', 'mistake', 'has', 'anything']
This is what i have这就是我所拥有的
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
You don't need re
.你不需要
re
。 Use str.casefold
:使用
str.casefold
:
[w for w in sentence.split() if "a" in w.casefold()]
Output:输出:
['Anyone', 'has', 'made', 'a', 'mistake', 'has', 'anything']
如果没有标点符号,您可以使用字符串拆分。
match_list = [s for s in sentence.split(' ') if 'a' in s.lower()]
Here's another variation :这是另一个变化:
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.