Python - 搜索包含字符串的列表项(匹配大小写)

时间:2015-07-13 20:31:53

标签: python regex list

我需要搜索列表中的任何项是否包含特定字符串。目前我使用此代码:

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

问题在于,如果我尝试搜索Height,我得到了这个:

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

我只需匹配Height元素中包含的Height 6',因此item [0]将是我需要的那个。最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

您可以拆分项目,然后查看:

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

演示:

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

作为一种更通用的方法,您可以使用正则表达式搜索您的模式:

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

演示:

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