startswith()是Python中的一个字符串方法,用于判断字符串是否以指定的子字符串开头。
它的语法如下:
str.startswith(prefix[, start[, end]])
参数说明:
- prefix:要检查的子字符串
- start(可选):指定开始检查的位置,默认为0,即从字符串的开头开始检查
- end(可选):指定结束检查的位置,默认为字符串的长度,即一直检查到字符串的末尾
该方法返回一个布尔值,如果字符串以指定的子字符串开头,则返回True,否则返回False。
下面是一些例子:
str1 = "Hello, world!" print(str1.startswith("Hello")) # True str2 = "apple" print(str2.startswith("ap")) # True str3 = "python is awesome" print(str3.startswith("is", 7, 14)) # True
在第一个例子中,字符串"Hello, world!"以"Hello"开头,所以startswith()返回True。在第二个例子中,字符串"apple"以"ap"开头,所以startswith()返回True。在第三个例子中,字符串"python is awesome"中的子字符串"is"在位置7至14之间,而且以该子字符串开头,所以startswith()返回True。