Python 字符串 index() 方法

定义和用法

index() 方法查找指定值的首次出现。

如果找不到该值,index() 方法将引发异常。

index() 方法与 find() 方法几乎相同,唯一的区别是,如果找不到该值,则 find() 方法将返回 -1。(请看下面的例子)

实例

例子 1

文字中 "welcome" 一词在哪里?

txt = "Hello, welcome to my world."

x = txt.index("welcome")

print(x)

运行实例

例子 2

字母 "e" 在文本中首次出现在哪里?

txt = "Hello, welcome to my world."

x = txt.index("e")

print(x)

运行实例

例子 3

如果只在位置 5 和 10 之间搜索时,字母 "e"首次首先在哪里?

txt = "Hello, welcome to my world."

x = txt.index("e", 5, 10)

print(x)

运行实例

例子 4

如果找不到该值,则 find() 方法返回 -1,但是 index() 方法将引发异常:

txt = "Hello, welcome to my world."

print(txt.find("q"))
print(txt.index("q"))

运行实例

语法

string.index(value, start, end)

参数

参数 描述
value 必需。要检索的值。
start 可选。在哪里开始检索。默认是 0。
end 可选。在哪里结束检索。默认是字符串的末尾。