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

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

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

if 'abc' in xs:

当前回答

如果您只需要知道“abc”是否在其中一项中,这是最短的方法:

if 'abc' in str(my_list):

注意:这假设“abc”是字母数字文本。如果“abc”可能只是一个特殊字符(即[]”,),请不要使用它。

其他回答

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

pattern=re.compile(r'abc') 

pattern.findall(mylist)
my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']

for item in my_list:
    if (item.find('abc')) != -1:
        print ('Found at ', item)
x = 'aaa'
L = ['aaa-12', 'bbbaaa', 'cccaa']
res = [y for y in L if x in y]

如果您只需要知道“abc”是否在其中一项中,这是最短的方法:

if 'abc' in str(my_list):

注意:这假设“abc”是字母数字文本。如果“abc”可能只是一个特殊字符(即[]”,),请不要使用它。

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?")