Python 的 str.startswith(~) 方法返回 boolean 指示字符串是否以指定的 prefix 开头。
参数
1. prefix | string
要在源字符串中检查的前缀。
2. start | int | optional
要开始搜索的源字符串的索引(包含)。默认情况下,start=0 。
3. end | int | optional
要停止搜索的源字符串的索引(不包括)。默认情况下,end= start + len(prefix) 。
返回值
单个 boolean 指示源字符串是否以指定的 prefix 开头。
例子
基本用法
要检查源字符串 'abc def' 是否以前缀 'ab' 开头:
x = 'abc def'
x.startswith('ab')
True
启动参数
要检查源字符串 'abc def' 是否以前缀 'ab' 开头,从索引位置 1 开始:
y = 'abc def'
y.startswith('ab', 1)
False
搜索从索引位置 1 开始,该位置位于 'b' 。由于 'bc' 与提供的 'ab' 前缀不匹配,因此返回 False。
结束参数
要检查源字符串 'abc def' 是否以前缀 'abc' 开头,从索引位置 0 (包含)开始并在索引位置 2 (不包含)结束:
z = "abc def"
z.startswith("abc", 0, 2)
False
搜索的起始位置是索引位置 0 ( 'a' ),搜索在索引位置 2 ( 'c' ) 之前结束。因此,我们检查字符串 'ab' 是否以前缀 'abc' 开头,返回 False 。
相关用法
- Python String startswith()用法及代码示例
 - Python String strip方法用法及代码示例
 - Python String strip()用法及代码示例
 - Python String splitlines()用法及代码示例
 - Python String split方法用法及代码示例
 - Python String splitlines方法用法及代码示例
 - Python String split()用法及代码示例
 - Python String swapcase()用法及代码示例
 - Python String swapcase方法用法及代码示例
 - 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 rjust方法用法及代码示例
 - Python String rpartition()用法及代码示例
 - Python String rpartition方法用法及代码示例
 
注:本文由纯净天空筛选整理自Isshin Inada大神的英文原创作品 Python String | startswith method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
