Tutorial Study Image

Python index()

Python 中的 index() 函数有助于返回给定子字符串在字符串中的位置或索引。如果未找到搜索的子字符串,它将引发异常。在这里,我们还可以通过字符串提供搜索的起始和结束点。


cstr.index(sub[, start[, end]] ) #where start & end should be integers
 

index() 参数

index() 函数接受三个参数。如果未提供起始和结束索引,则搜索将从零索引开始,直到字符串的末尾。此方法类似于 find() 方法,不同之处在于 find() 在未找到搜索的子字符串时将返回 -1,而 index() 方法会引发异常。

参数 描述 必需/可选
sub 要在字符串 str 中搜索的子字符串 必需
开始 (start) 从此索引开始搜索 可选
 end 搜索子字符串直到此索引 可选

index() 返回值

此方法的输出应为表示子字符串位置的整数值。如果找到多个子字符串,它将只返回第一次出现的位置。

输入 返回值
如果子字符串  子字符串的索引
如果没有子字符串 ValueError 异常

Python 中 index() 方法的示例

示例 1:index() 如何仅使用子字符串参数?


string = 'Python is very easy to learn.'

result = string.index('very easy')
print("Substring 'very easy':", result)

result = string.index('Php')
print("Substring 'php':", result)
 

输出


Substring 'very easy': 10

Traceback (most recent call last):
  File "", line 6, in 
    result = string.index('Php')
ValueError: substring not found

示例 2:index() 如何使用 start 和 end 参数


string = 'Python is very easy to learn.'

# Substring is searched in 'very'
print(string.index('very', 6))

# Substring is searched in 'easy '
print(string.index('easy', 5, 10))

# Substring is searched in 'to'
print(string.index('to', 15, 23))
 

输出


10
Traceback (most recent call last):
  File "", line 7, in 
    print(quote.index('easy', 5, 10))
ValueError: substring not found
20