赞
踩
目录
startswith
是 Python 中的字符串方法,用于检查一个字符串是否以指定的前缀开头。如果字符串以指定的前缀开头,则返回 True,否则返回 False。
以下是 startswith
方法的语法:
str.startswith(prefix[, start[, end]])
prefix
:要检查的前缀字符串。start
(可选):指定开始搜索的位置,如果指定了该参数,则从该位置开始搜索前缀。end
(可选):指定结束搜索的位置,如果指定了该参数,则在该位置之前搜索前缀。- string = "Hello, world!"
- print(string.startswith("Hello")) # True
- print(string.startswith("World")) # False
-
- string = "www.example.com"
- print(string.startswith("www")) # True
- print(string.startswith("com")) # False
在第一个示例中,字符串 "Hello, world!" 以 "Hello" 开头,因此 startswith(Hello)
方法返回 True。而startswith(World)返回False
在第二个示例中,字符串 "www.example.com" 以 "www" 开头,因此 startswith(www)
方法返回 True。而startswith(com)返回False
- string = "Hello, world!"
-
- # 从第 1 个字符 (即e开始搜索) 开始搜索前缀 "Hel"
- result1 = string.startswith("Hel", 1)
- print(result1) # 输出:False
-
- result1 = string.startswith("el", 1)
- print(result1) # 输出:True
指定了开始搜索位置 1,那么就会从字符串第一个位置开始搜索,即从Hello中的e开始搜索
- string = "Hello, world!"
-
- # 在第 5 个字符之前结束搜索前缀 "ello"
- result2 = string.startswith("ello", 1, 5)
- print(result2) # 输出:True
-
- # 在第 4 个字符之前结束搜索前缀 "ello"
- result2 = string.startswith("ello", 1, 4)
- print(result2) # 输出:False
第一个,在指定位置1(e)开始搜索,5(,)前结束,所以ello是前缀,返回True
第二个,在指定位置1(e)开始搜索,4(o )前结束,所以ello不是前缀,返回False
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。