📜  Python string.index()方法

📅  最后修改于: 2020-10-30 06:15:24             🧑  作者: Mango

Python字符串index()方法

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

签名

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

参量

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

返回类型

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

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

Python字符串index()方法示例1

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

输出:

18

Python String index()方法示例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

Python字符串index()方法示例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