简体   繁体   中英

Python - Search a list item that contains a string (match case)

I need to search if any item of a list contains a specific string. At the moment I use this code:

mylist = ['Hometown City Heights', 'Height 6'', 'First name Mike']   
item = [s for s in mylist if "First name" in s]
print item[0]
>> First name Mike

The problem is that if I try so search Height I got this:

mylist = ['Hometown City Heights', 'Height 6'', 'First name Mike']   
item = [s for s in mylist if "Height" in s]
print item[0]
>> Hometown City Heights

I need to match only Height included in Height 6' element, so that item[0] will be the one that I need. What's the best way to do that?

You can split your items and then check :

item = [s for s in mylist if "Height" in s.split()]

Demo :

>>> mylist = ['Hometown City Heights', "Height 6'"]
>>> [s for s in mylist if "Height" in s.split()]
["Height 6'"]
>>> 

As a more general way you can use regex to search for your pattern :

import re
[s for s in mylist if re.search(r'\b{}\b'.format(pattern),s)]

Demo:

>>> pattern='First name'
>>> [s for s in mylist if re.search(r'\b{}\b'.format(pattern),s)]
['First name Mike']

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