python判断字符串是否包含子串
2022-12-14 本文已影响0人
_Irving
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