验证列表的元素是否在字符串中

时间:2016-07-22 01:50:35

标签: python string list

验证列表中的元素是否为字符串

我有一个关键词列表:

check_list  = ['aaa','bbb','ccc']

一组字符串:

test_string_1 = 'hellor world ccc'
test_string_2 = 'hellor world 2'

我想验证列表中的任何元素是否在字符串

for key in check_list:
    if key in test_string_1:
        print 'True'

但不是打印值返回True或False

所以我可以这样做:

if some_conditions or if_key_value_in_test_string:
    do something

2 个答案:

答案 0 :(得分:3)

如果我理解你想要的东西,你可以这样做:

def test(check_list, test_string)
    for key in check_list:
        if key in test_string:
            return True
    return False

或您可以单行:

any([key in test_string for key in check_list])

或使用生成器表达式,这可能对长列表有利,因为它会短路(即,在第一个True停止而不首先构建完整列表):

any(key in test_string for key in check_list)

答案 1 :(得分:2)

使用内置函数

>>> check_list  = ['aaa','bbb','ccc']
>>> test_string_1 = 'hellor world ccc'
>>> test_string_2 = 'hellor world 2'
>>> any([(element in test_string_1) for element in check_list])
True
>>> any([(element in test_string_2) for element in check_list])
False
>>> 
相关问题