Python find()函数使用详解

「作者主页」:士别三日wyx
「作者简介」:CSDN top100、阿里云博客专家、华为云享专家、网络安全领域优质创作者
「推荐专栏」:小白零基础《Python入门到精通》

find() 可以「检测」字符串中是否「包含指定字符串」

语法

string.find( str, start, end)

参数

  • str :(必选)指定需要检测的字符串
  • start :(可选)开始索引,默认为0 start = 0
  • end :(可选)结束索引,默认为字符串的长度 end = len(string)

返回值

  • 如果「包含」字符串,就返回字符串的索引
  • 如果「不包含」字符串,就返回 -1

实例:检测字符串 ‘hello world’ 中是否包含字符串 ‘e’

str1 = 'hello world'
print(str1.find('e'))

输出:

1

1、指定检索位置

只给 start ,不给 end ,默认搜索到字符串的「末尾」,搜索范围是 [start, 末尾]

比如从索引3开始,到末尾结束,检测字符串 ‘e’ 是否存在

str1 = 'hello hello'
print(str1.find('e', 3))

输出:

7

从结果可以看出,‘e’ 存在,并返回了 ‘e’ 的索引位置。

同时给 start end ,搜索范围含头不含尾 [start, end)

比如从索引3开始,到索引7结束,检测字符串 ‘e’ 是否存在

str1 = 'hello hello'
print(str1.find('e', 3, 7))
print(str1.find('e', 3, 8))

输出:

-1
7

从结果可以看出,‘e’ 的索引是7,当end为7时,因为搜索「含头不含尾」,所以没找到,就返回了 -1。


2、参数为负数

start end 可以为「负数」

从右边数第4个开始,到末尾结束,检测 ‘e’ 是否存在

str1 = 'hello hello'
print(str1.find('e', -4))

输出:

7

从右边数第4个开始,到从右边数第3个结束,检测 ‘e’ 是否存在

str1 = 'hello hello'
print(str1.find('e', -4, -3))
print(str1.find('e', -4, -4))

输出:

7
-1

3、超出范围

如果搜索的索引「超过」了字符串的「长度」,就会返回 -1,而不是报错。

即使搜索的子字符串长度超过了字符串的长度也不会报错。

str1 = 'hello'
print(str1.find('e', 11))
print(str1.find('hello world'))

输出:

-1
-1

3、find()和index()的区别?

find() index() 都能检测字符串是否存在,但如果找不到值, find() 会返回-1,而 index() 会报错 ValueError: substring not found

str1 = 'hello hello'
print(str1.find('a'))
print(str1.index('a'))

输出:

在这里插入图片描述

4、find()和rfind()的区别?

find() rfind() 都可以检测字符串是否存在,不同的是, find() 「左侧」开始查找,而 rfind() 「右侧」开始查找。

str1 = 'hello hello'
print(str1.find('e'))
print(str1.rfind('e'))

输出:

1
7

猜你喜欢

转载自blog.csdn.net/wangyuxiang946/article/details/131456147
今日推荐