如何检查字符串是否是字符串列表中项目的子字符串? [英] How to check if a string is a substring of items in a list of strings?
本文介绍了如何检查字符串是否是字符串列表中项目的子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个清单:
my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
并且想要搜索包含字符串 'abc'
的项目.我该怎么做?
and want to search for items that contain the string 'abc'
. How can I do that?
if 'abc' in my_list:
将检查列表中是否存在 'abc'
但它是 'abc-123'
和 'abc-456'
的一部分>, 'abc'
本身不存在.那么如何获取包含 'abc'
的所有项目?
would check if 'abc'
exists in the list but it is a part of 'abc-123'
and 'abc-456'
, 'abc'
does not exist on its own. So how can I get all items that contain 'abc'
?
推荐答案
如果您只想检查列表中任何字符串中是否存在abc
,您可以尝试
If you only want to check for the presence of abc
in any string in the list, you could try
some_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
if any("abc" in s for s in some_list):
# whatever
如果你真的想得到所有包含abc
的项目,使用
If you really want to get all the items containing abc
, use
matching = [s for s in some_list if "abc" in s]
这篇关于如何检查字符串是否是字符串列表中项目的子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文