要查找子字符串在字符串中的位置索引,可以使用字符串的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異常。