Python中index()和find()函数有何区别?

2026-06-11 10:171阅读0评论SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计402个文字,预计阅读时间需要2分钟。

Python中index()和find()函数有何区别?

发现了Python中的`index()`和`find()`方法的功能相似,但在百度上发现它们还是有一些不同。以下是一个简单的例子:

pythonmsg=mynameishelieprint(msg.index(m))print(msg.find(m))

输出结果为:

00

进程结束,退出码为0。

发现了python中的index()和find()实现的功能相似,去百度发现还是有不一样的。

Python中index()和find()函数有何区别?

先来个正常的 

msg = "mynameishelie" print(msg.index("m")) print(msg.find("m"))

输出结果为:

0
0

Process finished with exit code 0

继续

msg = "mynameishelie" print(msg.index("L")) print(msg.find("L"))


输出结果为:提示 substring not found

Traceback (most recent call last):
File "C:/Users/PycharmProjects/python/index_find.py", line 28, in <module>
print(msg.index("L"))
ValueError: substring not found

Process finished with exit code 1

好了,下面来找下index的语法使用:

def index(self, sub, start=None, end=None):

# Like S.find() but raise ValueError when the substring is not found.
可以看出index()相当于find(),但是在没有找到子串的时候会有报错,影响程序执行。

再来看看find的语法使用:

def find(self, sub, start=None, end=None):

# Return the lowest index in S where substring sub is found,# such that sub is contained within S[start:end]. Optional# arguments start and end are interpreted as in slice notation.# Return -1 on failure.和index()不同的是find()在找不到substring时不会抛出异常,而是会返回-1,因此不会影响程序的执行。

标签:差异发现

本文共计402个文字,预计阅读时间需要2分钟。

Python中index()和find()函数有何区别?

发现了Python中的`index()`和`find()`方法的功能相似,但在百度上发现它们还是有一些不同。以下是一个简单的例子:

pythonmsg=mynameishelieprint(msg.index(m))print(msg.find(m))

输出结果为:

00

进程结束,退出码为0。

发现了python中的index()和find()实现的功能相似,去百度发现还是有不一样的。

Python中index()和find()函数有何区别?

先来个正常的 

msg = "mynameishelie" print(msg.index("m")) print(msg.find("m"))

输出结果为:

0
0

Process finished with exit code 0

继续

msg = "mynameishelie" print(msg.index("L")) print(msg.find("L"))


输出结果为:提示 substring not found

Traceback (most recent call last):
File "C:/Users/PycharmProjects/python/index_find.py", line 28, in <module>
print(msg.index("L"))
ValueError: substring not found

Process finished with exit code 1

好了,下面来找下index的语法使用:

def index(self, sub, start=None, end=None):

# Like S.find() but raise ValueError when the substring is not found.
可以看出index()相当于find(),但是在没有找到子串的时候会有报错,影响程序执行。

再来看看find的语法使用:

def find(self, sub, start=None, end=None):

# Return the lowest index in S where substring sub is found,# such that sub is contained within S[start:end]. Optional# arguments start and end are interpreted as in slice notation.# Return -1 on failure.和index()不同的是find()在找不到substring时不会抛出异常,而是会返回-1,因此不会影响程序的执行。

标签:差异发现