代码之家  ›  专栏  ›  技术社区  ›  WalkingRandomly

在列表中搜索子字符串的Python方式

  •  3
  • WalkingRandomly  · 技术社区  · 16 年前

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

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

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

    这很好,但我想知道是否有一个更好的方式(即更pythonic)这样做?

    迈克

    5 回复  |  直到 16 年前
        1
  •  15
  •   christopheml Eran Medan    16 年前

    您还可以使用列表理解:

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

    (如果你真的在寻找字符串 启动

    matches = [s for s in mytext if s.startswith('foobar')]
    
        2
  •  9
  •   Alex Martelli    16 年前

    如果您确实希望第一次出现以foobar开头的字符串(这是您的单词所说的,尽管与您的代码、提供的所有答案、您提到的grep——您能得到多大的矛盾?-),请尝试:

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

    这将提供一个空字符串作为 found next 内置默认值(仅限Python2.6及更高版本)。

        3
  •  6
  •   SilentGhost    16 年前
    for s in lst:
        if 'foobar' in s:
             print(s)
    
        4
  •  5
  •   Clay    16 年前
    results = [ s for s in lst if 'foobar' in s]
    print(results)
    
        5
  •  4
  •   Jochen Ritzel    16 年前

    如果你真的在寻找 使用foobar(不使用foobar 在里面

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

    found = [ s for s in mylist if s.startswith('foobar') ]
    
    推荐文章