index()
方法返回子字符串在字符串中(如果找到)的索引。如果未找到子字符串,它会引发异常。
示例
text = 'Python is fun'
# find the index of is
result = text.index('is')
print(result)
# Output: 7
index() 语法
其语法是
str.index(sub[, start[, end]] )
index() 参数
index()
方法接受三个参数
- sub - 要在字符串 str 中搜索的子字符串。
- start 和 end(可选)- 在 str[start:end] 范围内搜索子字符串
index() 返回值
- 如果字符串中存在子字符串,则返回找到子字符串的最低索引。
- 如果字符串中不存在子字符串,则会引发 ValueError 异常。
index()
方法与字符串的 find() 方法相似。
唯一的区别是,如果未找到子字符串,find() 方法返回 -1,而 index()
会抛出异常。
示例 1:仅带子字符串参数的 index()
sentence = 'Python programming is fun.'
result = sentence.index('is fun')
print("Substring 'is fun':", result)
result = sentence.index('Java')
print("Substring 'Java':", result)
输出
Substring 'is fun': 19 Traceback (most recent call last): File "<string>", line 6, in result = sentence.index('Java') ValueError: substring not found
注意: Python 中的索引从 0 开始,而不是 1。因此,出现位置是 19 而不是 20。
示例 2:带 start 和 end 参数的 index()
sentence = 'Python programming is fun.'
# Substring is searched in 'gramming is fun.'
print(sentence.index('ing', 10))
# Substring is searched in 'gramming is '
print(sentence.index('g is', 10, -4))
# Substring is searched in 'programming'
print(sentence.index('fun', 7, 18))
输出
15 17 Traceback (most recent call last): File "<string>", line 10, in print(quote.index('fun', 7, 18)) ValueError: substring not found
另请阅读