【问题标题】:Looking through a string but avoiding substring浏览字符串但避免子字符串
【发布时间】:2021-03-09 16:42:01
【问题描述】:

我需要检查一个字符串是否出现在文本中。我想避免子字符串。

string = "one"
text = "bees make honey

if string in text 

这当然返回 True。我该如何避免这个问题?

【问题讨论】:

  • 考虑在正则表达式中使用单词边界:wordboundary

标签: string replace substring


【解决方案1】:

嗯,“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')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-16
    • 1970-01-01
    • 2012-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-01
    • 2016-06-17
    相关资源
    最近更新 更多