在python中搜索字符串

2024-04-23 15:42:44 发布

您现在位置: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)

如何获得所需的输出?你知道吗


Tags: of字符串inhello列表forindexif
1条回答
网友
1楼 · 发布于 2024-04-23 15:42:44

如果您只想查看字符串是否包含作为单词的字符串,请添加空格,这样开始和结束看起来与正常单词边界相同:

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)

相关问题 更多 >