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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
