在Python中的列表中查找子字符串 [英] Finding a substring within a list in Python

查看:1354
本文介绍了在Python中的列表中查找子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例列表:mylist = ['abc123', 'def456', 'ghi789']

如果子字符串匹配,我想检索一个元素,例如abc

I want to retrieve an element if there's a match for a substring, like abc

sub = 'abc'
print any(sub in mystring for mystring in mylist)

如果列表中的任何元素包含模式,则上面打印True.

above prints True if any of the elements in the list contain the pattern.

我想打印与子字符串匹配的元素.因此,如果我要检查'abc',我只想从列表中打印'abc123'.

I would like to print the element which matches the substring. So if I'm checking 'abc' I only want to print 'abc123' from list.

推荐答案

print [s for s in list if sub in s]

如果要用换行符分隔它们:

If you want them separated by newlines:

print "\n".join(s for s in list if sub in s)

完整示例,不区分大小写:

Full example, with case insensitivity:

mylist = ['abc123', 'def456', 'ghi789', 'ABC987', 'aBc654']
sub = 'abc'

print "\n".join(s for s in mylist if sub.lower() in s.lower())

这篇关于在Python中的列表中查找子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆