共計 264 個字符,預計需要花費 1 分鐘才能閱讀完成。
要查找子字符串在字符串中的位置索引,可以使用字符串的 find()
方法或者 index()
方法。
使用 find()
方法:
s = "Hello, World!"
sub = "World"
index = s.find(sub)
print(index) # 輸出 7
使用 index()
方法:
s = "Hello, World!"
sub = "World"
index = s.index(sub)
print(index) # 輸出 7
如果子字符串不在原始字符串中,find()
方法會返回 -1,而 index()
方法會拋出一個 ValueError
異常。
丸趣 TV 網 – 提供最優質的資源集合!
正文完