Python String 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"))
自己動手試一試 »