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
"""
添加回答
舉報