Python 的 str.find(~)
方法返回源字符串中指定子字符串第一次出現的索引。
參數
1. sub
| string
要在源字符串中搜索的子字符串。
2. start
| number
| optional
開始搜索的源字符串的索引(包括)。默認為0
(源字符串的開頭)。
3. end
| number
| optional
結束搜索的源字符串的索引(不包括)。默認為 len(source string) + 1
。
返回值
如果找到子字符串,則返回源字符串中子字符串的第一個字符的索引。如果未找到,則返回-1
。
例子
基本用法
要獲取第一次出現 "bc"
的起始索引:
w = "abcdbc"
w.find("bc")
1
"abcdbc"
中 "bc"
的第一次出現出現在索引位置 1
(在 'a'
之後)。
未找到子字符串
要獲取第一次出現 "gg"
的起始索引:
x = "abcdbc"
x.find("gg")
-1
由於在 "abcdbc"
中未找到 "gg"
,因此返回 -1
。
啟動參數
從索引2
(含)開始搜索:
y = "abcdbc"
y.find("bc", 2)
4
由於搜索從索引位置 2
(第一個 'c'
)開始,因此 "bc"
第一次出現在索引位置 4
處。
結束參數
要停止在索引 3
處搜索(不包括):
z = "abcdbc"
z.find("cd", 3)
-1
由於搜索結束於索引位置 3
( 'd'
),因此未找到 "cd"
並返回 -1
。
相關用法
- Python String find()用法及代碼示例
- Python String format_map()用法及代碼示例
- Python String format方法用法及代碼示例
- Python String format()用法及代碼示例
- Python String format_map方法用法及代碼示例
- Python String count方法用法及代碼示例
- Python String isnumeric方法用法及代碼示例
- Python String Center()用法及代碼示例
- Python String zfill方法用法及代碼示例
- Python String rstrip方法用法及代碼示例
- Python String decode()用法及代碼示例
- Python String count()用法及代碼示例
- Python String join()用法及代碼示例
- Python String casefold()用法及代碼示例
- Python String isalnum()用法及代碼示例
- Python String endswith方法用法及代碼示例
- Python String rsplit()用法及代碼示例
- Python String isidentifier()用法及代碼示例
- Python String startswith()用法及代碼示例
- Python String rjust方法用法及代碼示例
- Python String rpartition()用法及代碼示例
- Python String rpartition方法用法及代碼示例
- Python String ljust方法用法及代碼示例
- Python String splitlines()用法及代碼示例
- Python String upper()用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 Python String | find method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。