Python 字串 find() 方法
示例
文字中“welcome”一詞出現在哪裡?
txt = "Hello, welcome to my world."
x = txt.find("welcome")
print(x)
自己動手試一試 »
定義和用法
find()
方法查詢指定值的第一個出現位置。
如果找不到該值,find()
方法將返回 -1。
find()
方法幾乎與 index()
方法相同,唯一的區別是,如果找不到值,index()
方法會引發異常。(見下例)
語法
string.find(value, start, end)
引數值
引數 | 描述 |
---|---|
value | 必需。要搜尋的值 |
start | 可選。開始搜尋的位置。預設為 0 |
end | 可選。結束搜尋的位置。預設為字串的末尾 |
更多示例
示例
當您只在位置 5 和 10 之間搜尋時,文字中字母“e”的第一個出現位置在哪裡?
txt = "Hello, welcome to my world."
x = txt.find("e", 5, 10)
print(x)
自己動手試一試 »
示例
如果找不到該值,find() 方法返回 -1,但 index() 方法會引發異常
txt = "Hello, welcome to my world."
print(txt.find("q"))
print(txt.index("q"))
自己動手試一試 »