无涯教程-Python3 - index(subsring, beginIndex, endIndex)函数

54 阅读1分钟

Python的 index()方法与find()方法相同,只是它在失败时返回错误。此方法返回第一个出现的子字符串的索引,如果找不到匹配项,则返回错误。

index - 语法

index(sub[, start[, end]])

index - 参数

  • sub    - 子字符串
  • start  - 开始索引一个范围
  • end    - 范围的最后一个索引

index - 返回类型

如果找到,则返回子字符串的索引,否则返回错误ValueError。

让无涯教程看一些示例来了解index()方法。

# Python index() function example
# 变量声明
str = "Welcome to the Learnfk."
# 函数调用
str2 = str.index("at")
# 显示结果
print(str2)

输出

18

如果找不到子字符串,则会引发错误。

# Python index() function example
# 变量声明
str = "Welcome to the Learnfk."
# 函数调用
str2 = str.index("ate")
# 显示结果
print(str2)

输出

ValueError: substring not found

无涯教程还可以将开始索引和结束索引作为参数传递,以使过程更具定制性。

# Python index() function example
# 变量声明
str = "Welcome to the Learnfk."
# 函数调用
str2 = str.index("p",19,21)
# 显示结果
print("p is present at :",str2,"index")

输出

p is present at : 20 index

参考链接

www.learnfk.com/python3/pyt…