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 | 可選。結束檢索的位置。默認是字符串的結尾。 |
更多實例
實例
字母 "e" 在文本總首次出現的位置:
txt = "Hello, welcome to my world." x = txt.find("e") print(x)
實例
如果只搜索位置 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"))