检查Python 2.7中列表条目中是否有字符串功能

时间:2017-05-15 12:08:19

标签: python string python-2.7 list

我有以下列表:

my_list = ['banana', 'apple', 'orange', 'pear']

我还有一个数据源,为我的Python代码提供字符串。我想要实现的是将字符串与列表中的任何条目进行比较,如果匹配,则返回一个值。数据馈送中提供的字符串可能只是部分匹配,因此,例如,可能存在字符串'anana''appl'。我希望脚本也检查这些部分字符串以查看它们是否存在于列表中(例如,如果'anana'是传递的字符串,则将其与my_list进行比较并匹配为True)。

到目前为止我的代码是:

my_list = ['banana', 'apple', 'orange', 'pear']
for entry in my_list:   
    if entry in my_string: #my_string being the passed variable string
        print "There is a match"     

如上所述,关键是部分匹配也返回true而不仅仅是完全匹配,所以我希望上面的代码在my_string = 'banan时返回true,例如。

有什么建议吗?

3 个答案:

答案 0 :(得分:3)

my_list = ['banana', 'apple', 'orange', 'pear']
for entry in my_list:   
    if my_string in entry: #my_string being the passed variable string
        print "There is a match"  

您编写的代码将检查给定搜索字符串中列表变量的部分字符串。但是你想做与之相反的事情。因此my_string in entry将以您希望的方式运作。

答案 1 :(得分:0)

在这里,这将为您提供部分或完整匹配的结果列表:

import re
regex = re.compile(entry)
matches = [e for e in my_list if re.match(regex, e)]
if len(matches) > 0:
    print "There is are matches:", matches

答案 2 :(得分:0)

我来自perl所以我用正则表达式来解决所有问题:

import re
my_string = 'anana'
my_list = ['banana', 'apple', 'orange', 'pear']


if [1 for item in my_list if re.search(my_string, item)]:
    print "There is a match"
如果

找不到任何内容,

搜索会返回None