Wal*_*mly 3 python string substring list
我有一个字符串列表 - 类似于
mytext = ['This is some text','this is yet more text','This is text that contains the substring foobar123','yet more text']
我想找到第一次出现以foobar开头的东西.如果我正在贪图,那么我会搜索foobar*.我目前的解决方案是这样的
for i in mytext:
    index = i.find("foobar")
    if(index!=-1):
        print i
哪个工作正常,但我想知道是否有一个'更好'(即更pythonic)的方式这样做?
干杯,迈克
chr*_*eml 15
您还可以使用列表理解:
matches = [s for s in mytext if 'foobar' in s]
(如果你真的在寻找以'foobar' 开头的字符串,如THC4k注意到的那样,请考虑以下内容:
matches = [s for s in mytext if s.startswith('foobar')]
如果你真的想要第一次出现一个字符串,这个字符串开始使用foobar(这是你的话所说的,虽然与你的代码非常不同,提供的所有答案,你提到的grep - 你会得到多么矛盾? - ),试试:
found = next((s for s in mylist if s.startswith('foobar')), '')
found如果没有mylist项符合条件,则会给出一个空字符串作为结果.您也可以使用itertools等代替简单的genexp,但关键技巧是使用next带有默认值的内置函数(仅限Python 2.6和更好).
results = [ s for s in lst if 'foobar' in s]
print(results)