2015-12-23 2 views
0

Я пытаюсь найти элементы списка в строке в 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) 

output-

Absolute Index 
pH 

Когда я сделать следующее я не output-

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

Как я могу получить желаемый результат?

ответ

1

Не прибегая к регулярным выражениям, если вы просто хотите увидеть, если строка содержит строку, как слова, добавлять пробела, поэтому начало и конец выглядеть так же, как обычные границы слов:

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) 
Смежные вопросы