如何在以下列表中搜索包含字符串 'abc'
的项目?
xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
以下检查'abc'
是否在列表中,但未检测到'abc-123'
和'abc-456'
:
if 'abc' in xs:
最佳答案
检查列表中任何字符串中是否存在 '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]
关于python - 如何检查字符串是否是字符串列表中项目的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4843158/