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

2024-03-28 14:55:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何用字符串的一部分测试列表中的一个项。例如,如果一个列表包含“potatoechips”,而我有一个名为“potatoe”的字符串,那么如何检查该字符串是否在列表中的某个项目中找到?你知道吗

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

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

Tags: 项目字符串infalsetrue列表ifelse
3条回答

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

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

您正在使用in检查'potatoe'是否在列表中,但这将检查列表中的特定项是否正好是'potatoe'。你知道吗

只需遍历列表,然后检查:

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

>>> lst = ['potatoechips', 'icecream', 'donuts']
>>> stringInList('potatoe', lst)
True
>>> stringInList('rhubarb', lst)
False
>>> 

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

>>> li = ['potatoechips','icecream','donuts']
>>> s="potatoe"
>>> any(s in e for e in li)
True
>>> s="not in li"
>>> any(s in e for e in li)
False

优点是any会在第一个True中断,如果列表很长,效率会更高。你知道吗

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

>>> s in '|'.join(li)
True

这里的优势是如果你有很多测试。in例如,数百万次的测试比构建数百万次的理解要快。你知道吗

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

>>> li = ['potatoechips','icecream','donuts', 'potatoehash']
>>> s="potatoe"
>>> [(i,e) for i, e in enumerate(li) if s in e]
[(0, 'potatoechips'), (3, 'potatoehash')]

或者,您可以使用filter,如果您只是希望字符串作为替代:

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

相关问题 更多 >