一、函数介绍
Python str.find() 函数用于检测字符串中是否包含子字符串str,如果指定beg(开始)和 end(结束)范围,则检查是否包含在指定范围内。
二、函数语法
str.find(str, beg=0, end=len(string))
参数说明:
- str:指定检索的字符串
- beg:开始索引,默认值为0
- end:结束索引,默认为字符串长度len(string)
三、注意事项
1. 区分大小写
str.find()函数默认区分大小写,例如:
text = "Hello World"
index = text.find("world")   # 返回-1,表示未找到
如果要不区分大小写,可以使用字符串方法str.lower()将字符串转为小写再比较:
text = "Hello World"
index = text.lower().find("world")   # 返回6,表示找到了
2. 没有找到时返回-1
如果未能找到指定的子字符串,str.find()函数将返回-1:
text = "Hello World"
index = text.find("Python")   # 返回-1,表示未找到
可以根据是否返回-1来判断是否找到了子字符串:
if text.find("Python") == -1:
    print("未找到")
else:
    print("已找到")
四、使用示例
1. 检索字符串中是否包含指定的子字符串
text = "Python is a popular programming language."
 
if text.find("programming") != -1:
    print("包含子字符串")
else:
    print("不包含子字符串")
2. 按索引范围检索字符串
text = "Python is a popular programming language."
 
if text.find("program", 10, 20) != -1:
    print("在指定范围内找到子字符串")
else:
    print("不在指定范围内")
3. 不区分大小写的搜索
text = "Python is a popular programming language."
 
if text.lower().find("PROGRAMMING".lower()) != -1:
    print("找到子字符串")
else:
    print("没有找到子字符串")
4. 搜索并显示所有子字符串的位置
text = "Python is a popular programming language. Python is easy to learn."
search_string = "Python"
start = 0
 
while True:
    start = text.find(search_string, start)
    
    if start == -1:
        break
    
    print("子字符串位置:", start)
    start += 1
5. 搜索并替换子字符串
text = "Python is a popular programming language. Python is easy to learn."
new_text = text.replace("Python", "Java")
print(new_text)
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/283032.html
 
 微信扫一扫
微信扫一扫  支付宝扫一扫
支付宝扫一扫 