2015-12-23 72 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) 

輸出 -

Absolute Index 
pH 

當我這樣做我沒有得到任何輸出 -

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)