3

我有一个字符串列表 - 类似于

mytext = ['This is some text','this is yet more text','This is text that contains the substring foobar123','yet more text']

我想找到以 foobar 开头的任何内容的第一次出现。如果我是 grepping,那么我会搜索 foobar*。我目前的解决方案看起来像这样

for i in mytext:
    index = i.find("foobar")
    if(index!=-1):
        print i

哪个工作得很好,但我想知道是否有一种“更好”(即更pythonic)的方式来做到这一点?

干杯,迈克

4

5 回答 5

15

您还可以使用列表推导:

matches = [s for s in mytext if 'foobar' in s]

(如果您真的在寻找THC4k 注意到的以 'foobar'开头的字符串,请考虑以下内容:

matches = [s for s in mytext if s.startswith('foobar')]
于 2009-08-11T15:15:33.690 回答
9

如果您真的想要第一次出现以 foobar 开头的字符串(这就是您所说的,尽管与您的代码非常不同,提供的所有答案,您提到的 grep ——您能得到多大的矛盾?-),请尝试:

found = next((s for s in mylist if s.startswith('foobar')), '')

found如果 mylist 中没有任何项目满足条件,这将给出一个空字符串作为结果。您也可以使用 itertools 等来代替简单的 genexp,但关键技巧是这种使用next默认值的内置函数的方式(仅限 Python 2.6 和更好的版本)。

于 2009-08-11T15:39:34.203 回答
6
for s in lst:
    if 'foobar' in s:
         print(s)
于 2009-08-11T15:06:50.430 回答
5
results = [ s for s in lst if 'foobar' in s]
print(results)
于 2009-08-11T15:15:18.697 回答
4

如果您真的在寻找以 foobar开头的字符串(而不是 foobar 其中):

for s in mylist:
  if s.startswith( 'foobar' ):
     print s

或者

found = [ s for s in mylist if s.startswith('foobar') ]
于 2009-08-11T15:15:51.270 回答