美文网首页
python判断字符串是否包含子串

python判断字符串是否包含子串

作者: _Irving | 来源:发表于2022-12-14 13:49 被阅读0次
1、使用in 和 not in
>>> "llo" in "hello, python"
True
>>>
>>> "lol" in "hello, python"
False
2、使用find方法

如果找到子串,返回指定子串在字符串中的出现位置,没有找到就返回-1

>>> "hello, python".find("llo") != -1
True
>>> "hello, python".find("lol") != -1
False
>>
3、使用index方法

返回指定子串在该字符串中第一次出现的索引,如果没找到就会抛出异常

def is_in(full_str, sub_str):
    try:
        full_str.index(sub_str)
        return True
    except ValueError:
        return False

print(is_in("hello, python", "llo"))  # True
print(is_in("hello, python", "lol"))  # False
4、使用count方法

只要判断结果大于0就说明子串存在于字符串中

def is_in(full_str, sub_str):
    return full_str.count(sub_str) > 0

print(is_in("hello, python", "llo"))  # True
print(is_in("hello, python", "lol"))  # False
5、通过魔法方法

其实in和not in使用时,python解释器回先去检查该对象是有contains魔法方法

>>> "hello, python".__contains__("llo")
True
>>>
>>> "hello, python".__contains__("lol")
False
>>>
6、借助operator

operator模块是用c实现的,所以执行速度比python代码快

>>> import operator
>>>
>>> operator.contains("hello, python", "llo")
True
>>> operator.contains("hello, python", "lol")
False
>>> 

7、使用正则匹配

import re

def is_in(full_str, sub_str):
    if re.findall(sub_str, full_str):
        return True
    else:
        return False

print(is_in("hello, python", "llo"))  # True
print(is_in("hello, python", "lol"))  # False

相关文章

网友评论

      本文标题:python判断字符串是否包含子串

      本文链接:https://www.haomeiwen.com/subject/jldhqdtx.html