发现了python中的index()和find()实现的功能相似,去百度发现还是有不一样的。 先来个正常的 msg = "mynameishelie"print(msg.index("m"))print(msg.find("m")) 输出结果为: 0 0 Process finished with exit code 0 继
发现了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,因此不会影响程序的执行。