2 回答
TA贡献1744条经验 获得超4个赞
你可以用regex
那个会更容易,用.+
which的意思替换撇号
.
任何字符+
1次或多次
import re
words = ['banana', 'fish', 'scream', 'screaming', 'suncream', 'suncreams']
find = "s'cream"
pattern = re.compile(find.replace("'", ".+"))
for word in words:
if pattern.fullmatch(word):
print(word)
TA贡献1836条经验 获得超4个赞
使用正则表达式这很容易:
使用的选择\w+是与“单词”字符(如字母)匹配,并且要求至少有 1 个与其映射的字符。
import re
find = "s'cream"
words = [
"banana",
"fish",
"scream",
"screaming",
"suncream",
"suncreams"
]
target_re = re.compile("^{}$".format(find.replace("'", "\w+")))
for word in words:
if target_re.match(word):
print("Matched:", word)
else:
print("Not a match:", word)
"""
output:
Not a match: banana
Not a match: fish
Not a match: scream
Not a match: screaming
Matched: suncream
Not a match: suncreams
"""
添加回答
举报