简体   繁体   English

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

[英]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: 问题是,如果我尝试搜索“ 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

I need to match only Height included in Height 6' element, so that item[0] will be the one that I need. 我只需匹配Height包括在Height 6'的元素,所以该项目[0]将是我所需要的一个。 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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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