發現了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,因此不會影響程序的執行。