startswith()
是 Python 字符串对象的一个方法,用于检查字符串是否以指定的前缀开头。
str.startswith(prefix[, start[, end]])
prefix
:要检查的前缀字符串。start
(可选参数):检查的起始位置,默认为 0。end
(可选参数):检查的结束位置,默认为字符串的末尾。
该方法返回一个布尔值,表示字符串是否以指定的前缀开头。
sentence = "Hello, world!"
# 检查是否以 "Hello" 开头
result = sentence.startswith("Hello")
print(result)
# Output: True
# 检查是否以 "world" 开头(从索引 7 开始)
result = sentence.startswith("world", 7)
print(result)
# Output: True
# 检查是否以 "Hola" 开头
result = sentence.startswith("Hola")
print(result)
# Output: False