2020-05-27
阅读量:
1111
python中 index()和find()的区别
发现了python中的index()和find()实现的功能相似,去百度发现还是有不一样的。
先来个正常的
msg = "mynameishelie"
print(msg.index("m"))
rint(msg.find("m"))
输出结果为:0
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,因此不会影响程序的执行。






评论(0)


暂无数据
推荐帖子
0条评论
0条评论
3条评论