【发布时间】:2021-03-09 16:42:01
【问题描述】:
我需要检查一个字符串是否出现在文本中。我想避免子字符串。
string = "one"
text = "bees make honey
if string in text
这当然返回 True。我该如何避免这个问题?
【问题讨论】:
-
考虑在正则表达式中使用单词边界:wordboundary
我需要检查一个字符串是否出现在文本中。我想避免子字符串。
string = "one"
text = "bees make honey
if string in text
这当然返回 True。我该如何避免这个问题?
【问题讨论】:
嗯,“one”确实作为子字符串出现在“bees make honey”中。
但是如果你想看看“one”是不是一个单词,你可以使用split() 函数。
我所说的文字是指蜜蜂、制造和蜂蜜。
示例 python 实现:
l = parentString.split(' ') # Returns ['bees','make','honey']
if childString in l:
print('Word found in parent text')
else:
print('Word not found in parent text')
【讨论】: