简体   繁体   中英

Searching in a string in python

I am trying to search for items of a list in a string in python.

This is my list and the string.

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

The output I want is Absolute Index . When I try to search it as a substring I also get pH.

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

Output-

Absolute Index
pH

When I do the following I get no output-

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

How can I get the desired output?

Without resorting to regexes, if you want to just see if the string contains a string as words, add spaces, so the beginning and end look the same as normal word boundaries:

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)

With regexes, you'd do:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM