在python中搜索字符串

时间:2015-12-23 02:13:58

标签: python

我正在尝试在python中搜索字符串中列表的项目。

这是我的清单和字符串。

list1=['pH','Absolute Index','Hello']
sring1='lekpH Absolute Index of New'

我想要的输出是Absolute Index。当我尝试将其作为子串搜索时,我也会得到pH值。

for item in list1:
    if item in sring1:
        print(item)

输出 -

Absolute Index
pH

当我执行以下操作时,我没有输出 -

for item in list1:
    if item in sring1.split():
        print(item)

如何获得所需的输出?

1 个答案:

答案 0 :(得分:0)

如果你不想使用正则表达式,如果你只想查看字符串是否包含字符串作为单词,请添加空格,因此开头和结尾看起来与普通单词边界相同:

list1=['pH','Absolute Index','Hello']
sring1='lekpH Absolute Index of New'

# Add spaces up front to avoid creating the spaced string over and over
# Do the same for list1 if it will be reused over and over
sringspaced = ' {} '.format(sring1)

for item in list1:
    if ' {} '.format(item) in sringspaced:
        print(item)

使用正则表达式,您可以:

import re

# \b is the word boundary assertion, so it requires that there be a word
# followed by non-word character (or vice-versa) at that point
# This assumes none of your search strings begin or end with non-word characters
pats1 = [re.compile(r'\b{}\b'.format(re.escape(x))) for x in list1]

for item, pat in zip(list1, pats1):
    if pat.search(sring1):
        print(item)