在列表中搜索子字符串的Python方法 [英] Pythonic way of searching for a substring in a list

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

问题描述

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

I have a list of strings - something like

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

我想找到以foobar开头的任何东西的第一次出现.如果我正在grepping,那么我将搜索foobar *.我目前的解决方案是这样的

I want to find the first occurrence of anything that starts with foobar. If I was grepping then I would do search for foobar*. My current solution looks like this

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

哪种方法工作得很好,但我想知道是否有一种更好"(即更Python化)的方法?

Which works just fine but I am wondering if there is a 'better' (i.e more pythonic) way of doing this?

干杯, 迈克

推荐答案

您还可以使用列表推导:

You can also use a list comprehension :

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

(并且,如果您确实在寻找以'foobar'开头的字符串开头,请注意以下内容:

(and if you were really looking for strings starting with 'foobar' as THC4k noticed, consider the following :

matches = [s for s in mytext if s.startswith('foobar')]

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

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