python - 检查带有前导和尾随空格的子字符串是否在字符串中

想象一下我需要检查是否在

longString = "this is a long sting where a lo must be detected."

包含作为单词的子字符串 lo。我需要像 " lo " 一样使用前导和尾随空格来检测它。我该怎么做?

(更复杂的是,搜索字符串来自像 [' lo ','bar'] 这样的字符串列表。我知道解决方案 https://stackoverflow.com/questions/3389574/check-if-multiple-strings-exist-in-another-string

回答1

你可以使用正则表达式......

import re

seq = ["  lo  ", "bar"]
pattern = re.compile(r"^\s*?lo\s*?$")
for i in seq:
    result = pattern.search(i)
    if result:                  #  does match
        ... do something
    else:                       #  does not match
        continue

回答2

为什么不在开始检查匹配项是否在字符串中之前清理字符串以删除空格,这样您就不必处理这种情况?

做类似的事情

" lo " .strip() 变成 'lo'

相似文章

随机推荐

最新文章