温馨提示×

Python怎么查找子字符串在字符串中的位置索引

小亿
95
2024-03-02 13:20:25
栏目: 编程语言

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

0