使用in关键字可直接判断子串是否存在,如if substring in text:,返回True或False;find()返回索引或-1,index()找到返回索引否则抛异常,正则re.search()支持复杂匹配,忽略大小写可用lower()或re.IGNORECASE。

Python检查字符串是否包含子串,方法有很多,最常用也最直接的就是使用
in
find()
index()
in
使用
in
True
False
in
直接上例子最清楚:
text = "Hello, world!"
substring = "world"
if substring in text:
print("子串存在!")
else:
print("子串不存在!")这段代码会输出 "子串存在!"。
in
立即学习“Python免费学习笔记(深入)”;
find()
index()
find()
index()
ValueError
text = "Hello, world!"
substring = "world"
# find()
index = text.find(substring)
if index != -1:
print(f"子串在索引 {index} 处找到")
else:
print("子串未找到")
# index()
try:
index = text.index(substring)
print(f"子串在索引 {index} 处找到")
except ValueError:
print("子串未找到")选择哪个取决于你的需求。如果你不希望处理异常,
find()
index()
正则表达式功能强大,但通常也更复杂。
re
search()
import re
text = "Hello, world!"
substring = "world"
match = re.search(substring, text)
if match:
print("子串存在!")
else:
print("子串不存在!")正则表达式的优势在于可以进行更复杂的模式匹配,比如模糊匹配、大小写不敏感匹配等。但对于简单的子串判断,
in
如果需要忽略大小写,可以将字符串和子串都转换为小写(或大写)再进行判断。
text = "Hello, World!"
substring = "world"
if substring.lower() in text.lower():
print("子串存在(忽略大小写)!")
else:
print("子串不存在(忽略大小写)!")或者,使用正则表达式,可以设置
re.IGNORECASE
import re
text = "Hello, World!"
substring = "world"
match = re.search(substring, text, re.IGNORECASE)
if match:
print("子串存在(忽略大小写)!")
else:
print("子串不存在(忽略大小写)!")具体选择哪种方法,取决于你的具体需求和个人偏好。
in
以上就是python如何检查字符串中是否包含子串_python判断字符串包含子串的方法的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号