Python 字符串 index() 方法

實例

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

txt = "Hello, welcome to my world."
x = txt.index("welcome")
print(x)

運行實例

定義和用法

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

如果找不到該值,index() 方法將引發異常。

index() 方法與 find() 方法幾乎相同,唯一的區別是,如果找不到該值,則 find() 方法將返回 -1。(請看下面的例子)

語法

string.index(value, start, end)

參數值

參數 描述
value 必需。要檢索的值。
start 可選。在哪里開始檢索。默認是 0。
end 可選。在哪里結束檢索。默認是字符串的末尾。

更多實例

實例

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

txt = "Hello, welcome to my world."
x = txt.index("e")
print(x)

運行實例

實例

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

txt = "Hello, welcome to my world."
x = txt.index("e", 5, 10)
print(x)

運行實例

實例

如果找不到該值,則 find() 方法返回 -1,但是 index() 方法將引發異常:

txt = "Hello, welcome to my world."
print(txt.find("q"))
print(txt.index("q"))

運行實例