
如果字符串以指定的前缀(字符串)开头,则startswith()方法将返回True。如果不是,则返回False。
startswith()的语法为:
str.startswith(prefix[, start[, end]])
startswith()参数
startswith()方法最多使用三个参数:
- prefix -要检查的字符串或字符串元组 
- start(可选)- 要在字符串中检查前缀的开始位置。 
- end (可选)- 要在字符串中检查前缀的结束位置。 
startswith()返回值
startswith()方法返回一个布尔值。
- 如果字符串以指定的前缀开头,则返回True。 
- 如果字符串不是以指定的前缀开头,则返回False。 
示例1:startswith()没有start和end参数
text = "Python is easy to learn."
result = text.startswith('is easy')
# 返回 False
print(result)
result = text.startswith('Python is ')
# 返回 True
print(result)
result = text.startswith('Python is easy to learn.')
# 返回 True
print(result)运行该程序时,输出为:
False True True
示例2:startswith()带start和end参数
text = "Python programming is easy."
#起始参数: 7
# 'programming is easy.' 字符串被搜索
result = text.startswith('programming is', 7)
print(result)
# start: 7, end: 18
# 'programming' 字符串被搜索
result = text.startswith('programming is', 7, 18)
print(result)
result = text.startswith('program', 7, 18)
print(result)运行该程序时,输出为:
True False True
将元组传递给startswith()
在Python中可以将前缀的元组传递给startswith()方法。
如果字符串以元组的任何项目开头,则startswith()返回True。如果不是,则返回False
示例3:具有元组前缀的startswith()
text = "programming is easy"
result = text.startswith(('python', 'programming'))
# 输出 True
print(result)
result = text.startswith(('is', 'easy', 'java'))
# 输出 False
print(result)
# 带start 和 end 参数
# 'is easy'字符串被检查
result = text.startswith(('programming', 'easy'), 12, 19)
# 输出 False
print(result)运行该程序时,输出为:
True False False
如果需要检查字符串是否以指定的后缀结尾,则可以在Python中使用endswith()方法。
