如何检查一个字符串是否是字符串列表中的子串
我该如何在下面的列表中搜索包含字符串 'abc'
的项目呢?
xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
下面的代码检查 'abc'
是否在列表中,但它无法找到 'abc-123'
和 'abc-456'
:
if 'abc' in xs:
17 个回答
107
使用 filter
函数可以找到所有包含 'abc'
的元素:
>>> xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
>>> list(filter(lambda x: 'abc' in x, xs))
['abc-123', 'abc-456']
你也可以用列表推导式来实现这个功能:
>>> [x for x in xs if 'abc' in x]
238
我来分享一个小技巧:如果你需要同时匹配多个字符串,比如 abc
和 def
,你可以把两个列表推导式结合起来,像这样:
matchers = ['abc','def']
matching = [s for s in my_list if any(xs in s for xs in matchers)]
输出结果:
['abc-123', 'def-456', 'abc-456']
1363
要检查列表中的任何字符串是否包含 'abc'
:
xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
if any("abc" in s for s in xs):
...
要获取所有包含 'abc'
的项目:
matching = [s for s in xs if "abc" in s]