Python 字符串 index()方法

Python 字符串 index()方法

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

语法

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

参数

  • sub : 子字符串
  • start : 起始索引
  • end : 结束索引(不包含)

返回类型

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

让我们看一些示例来理解 index() 方法。

示例1

# Python index() function example
# Variable declaration
str = "Welcome to the Javatpoint."
# Calling function
str2 = str.index("at")
# Displaying result
print(str2)

输出:

18

示例2

如果找不到子字符串,则会抛出错误。

# Python index() function example
# Variable declaration
str = "Welcome to the Javatpoint."
# Calling function
str2 = str.index("ate")
# Displaying result
print(str2)

输出:

ValueError: substring not found

示例3

我们还可以传递起始和结束索引作为参数,以使过程更加定制化。

# Python index() function example
# Variable declaration
str = "Welcome to the Javatpoint."
# Calling function
str2 = str.index("p",19,21)
# Displaying result
print("p is present at :",str2,"index")

输出:

p is present at : 20 index

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程