Python 字符串的 index() 方法
index()
方法返回子字符串在给定字符串中第一次出现的索引。它与 find() 方法相同,不同之处在于如果找不到子字符串,它会引发异常。
语法
str.index(substr, start, end)
参数
- substr: (必需) 要查找索引的子字符串。
- start: (可选) 字符串中开始搜索的起始索引位置。默认为 0。
- end: (可选) 字符串中搜索结束的索引位置。默认为字符串的末尾。
返回值
一个整数值,表示指定子字符串的索引。
以下示例演示了 index()
方法。
示例: index()
greet='Hello World!' print('Index of H: ', greet.index('H')) print('Index of e: ', greet.index('e')) print('Index of l: ', greet.index('l')) print('Index of World: ', greet.index('World'))
输出
Index of H: 0 Index of e: 1 Index of l: 2 Index of World: 6
index()
方法只返回第一次出现的索引。
示例: index() 返回第一次出现的索引
greet='Hello World' print('Index of l: ', greet.index('l')) print('Index of o: ', greet.index('o'))
输出
Index of l: 2 Index of o: 4
index()
方法执行区分大小写的搜索。如果找不到子字符串,它会抛出 ValueError
。
示例: 区分大小写的 index() 方法
greet='Hello World' print(greet.index('h')) # throws error: substring not found print(greet.index('hello')) # throws error
输出
ValueError: substring not found ValueError: substring not found
如果找不到给定的子字符串,它将抛出错误。
示例: index()
mystr='TutorialsTeacher is a free online learning website' print(mystr.index('python'))
输出
Traceback (most recent call last) <ipython-input-3-a72aac0824ca> in <module> 1 str='TutorialsTeacher is a free online learning website' ----> 2 print(str.index('python')) ValueError: substring not found
使用 start 和 end 参数将子字符串的搜索限制在指定的起始和结束索引之间。
示例: 带 start 和 end 参数的 index()
mystr='tutorialsteacher is a free tutorials website' print(mystr.index('tutorials',10)) # search starts from 10th index print(mystr.index('tutorials',1, 26)) # throws error; searches between 1st and 26th index
输出
27 ValueError: substring not found