Python str.find() 用法與範例

本篇 ShengYu 要介紹 Python str.find() 用法與範例,搜尋字串是字串處理中經常使用到的功能,在 Python 中的 str 已經內建提供了 find() 成員函式可以使用。

Python 的 str.find() 定義如下,

1
str.find(sub[, start[, end]])

sub:要搜尋的字串
start:為開始搜尋的位置,預設從索引值 0 開始搜尋
end:結束搜尋的位置,預設為該字串 str 的尾端

如果有找到的話會回傳找到的索引位置,沒有找到的話則會回傳 -1,

不管是一個字元或一個字元以上都可以用 str.find(),假如搜尋的字串為一個字元以上,例如 wo ,有找到的話是回傳開始的索引值唷!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

s = 'hello world'
found = s.find('w')
print(found)
found = s.find('wo')
print(found)
found = s.find('wo', 3)
print(found)
found = s.find('wo', 9)
print(found)
found = s.find('x')
print(found)
found = s.find('xx')
print(found)

輸出結果如下,

1
2
3
4
5
6
6
6
6
-1
-1
-1

其它相關文章推薦
如果你想學習 Python 相關技術,可以參考看看下面的文章,
Python 新手入門教學懶人包
Python list 串列用法與範例
Python set 集合用法與範例
Python dict 字典用法與範例
Python tuple 元組用法與範例