如何在以下列表中搜索包含字符串“abc”的项目?

xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456']

以下检查“abc”是否在列表中,但未检测到“abc-123”和“abc-456”:

if 'abc' in xs:

当前回答

mylist=['abc','def','ghi','abc']

pattern=re.compile(r'abc') 

pattern.findall(mylist)

其他回答

使用Pythons字符串类的__contains__()方法。:

a = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
for i in a:
    if i.__contains__("abc") :
        print(i, " is containing")
for item in my_list:
    if item.find("abc") != -1:
        print item

要检查列表中任何字符串中是否存在“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]
def find_dog(new_ls):
    splt = new_ls.split()
    if 'dog' in splt:
        print("True")
    else:
        print('False')


find_dog("Is there a dog here?")

我需要与以下匹配项对应的列表索引:

lst=['abc-123', 'def-456', 'ghi-789', 'abc-456']

[n for n, x in enumerate(lst) if 'abc' in x]

输出

[0, 3]