Python的 index()方法与find()方法相同,只是它在失败时返回错误。此方法返回第一个出现的子字符串的索引,如果找不到匹配项,则返回错误。
index(sub[, start[, end]])
如果找到,则返回子字符串的索引,否则返回错误ValueError。
链接:https://www.learnfk.comhttps://www.learnfk.com/python3/python-string-index-method.html
来源:LearnFk无涯教程网
让无涯教程看一些示例来了解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
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)