在Python中检查字符串是否被包含在另一个字符串中

Python可以非常轻易检查某个字符串是否包含在另一个字符串中,方法比较多。

使用in函数(最简单)

if "ABCD" in "xxxxABCDyyyy":
    # whatever

我自己在实践中有一个简单的案例检查字典的索引是否包含某个字符串,如果包含则提取索引对应的值(见本地变量分配前被引用报错"local variable 'XXX' referenced before assignment"

        INSTANCETYPE_STRING=self.machine_type
        cpu_base_set = {"SMALL": 1, "MEDIUM": 2, "LARGE": 4}
        for typeKey in cpu_base_set.keys():
            if typeKey in INSTANCETYPE_STRING:
                cpu_base = cpu_base_set[typeKey]
                type_base = typeKey

Check if multiple strings exist in another string有一个巧妙的案例,使用了any库函数:

a = ['a', 'b', 'c']
str = "a123"

if any(x in str for x in a):
    print "some of the strings found in str"

使用index函数

使用find函数

使用re函数

Does Python have a string 'contains' substring method?问答中,有人对比了不同方法的效率,in函数速度最快,find其次,index最慢。

输出:

参考

Last updated

Was this helpful?