如何在python中测试字符串的一部分是否等于列表中的一项?

如何在python中测试字符串的一部分是否等于列表中的一项?,python,string,list,Python,String,List,我正在尝试找出如何测试列表中包含部分字符串的项。例如,如果一个列表包含“potatoechips”,并且我有一个名为“potatoe”的字符串,我如何检查该字符串是否在列表中的某个项目中找到 list = ['potatoechips','icecream','donuts'] if 'potatoe' in list: print true else: false 您正在使用中的检查列表中是否有'potatoe',但这将检查列表中的特定项目是否恰好是'potatoe' 只需

我正在尝试找出如何测试列表中包含部分字符串的项。例如,如果一个列表包含“potatoechips”,并且我有一个名为“potatoe”的字符串,我如何检查该字符串是否在列表中的某个项目中找到

list = ['potatoechips','icecream','donuts']

if 'potatoe' in list:
    print true
else:
    false

您正在使用
中的
检查列表中是否有
'potatoe'
,但这将检查列表中的特定项目是否恰好是
'potatoe'

只需迭代列表,然后检查:

def stringInList(str, lst):
    for i in lst:
        if str in i:
            return True
    return False


要仅测试列表中任何字符串中是否存在子字符串,可以使用:

优点是
任何
都会在第一个
True
时中断,如果列表较长,则效率会更高

您还可以将列表合并为一个由分隔符分隔的字符串:

>>> s in '|'.join(li)
True
这里的优势是如果你有很多测试<例如,数百万次测试中的code>比构建数百万次理解要快

如果您想知道哪个字符串是正数,您可以使用列表理解和列表中字符串的索引:

>>> li = ['potatoechips','icecream','donuts', 'potatoehash']
>>> s="potatoe"
>>> [(i,e) for i, e in enumerate(li) if s in e]
[(0, 'potatoechips'), (3, 'potatoehash')]
或者,如果您只想使用字符串作为替代,可以使用
过滤器

>>> filter(lambda e: s in e, li)
['potatoechips', 'potatoehash']

您可以使用
string.find(sub)
方法验证子字符串是否在字符串中:

li = ['potatoechips', 'icecream', 'donuts']
for item in li:
    if item.find('potatoe') > -1:
        return True
else:
    return False
可以使用and list将列表筛选为类似的单词

list = ['potatoechips','icecream','donuts']
m = 'potatoe'
l = any(x for x in list if m in x)
print(l)
li = ['potatoechips', 'icecream', 'donuts']
for item in li:
    if item.find('potatoe') > -1:
        return True
else:
    return False
list = ['potatoechips','icecream','donuts']
m = 'potatoe'
l = any(x for x in list if m in x)
print(l)