startswith()
方法返回 True
,如果一个字符串以指定的`prefix`(字符串)开头。如果不是,则返回 False
。
示例
message = 'Python is fun'
# check if the message starts with Python
print(message.startswith('Python'))
# Output: True
字符串 startswith() 的语法
startswith()
的语法是
str.startswith(prefix[, start[, end]])
startswith() 参数
startswith()
方法最多接受三个参数
- prefix - 要检查的字符串或字符串元组
- start (可选) - 字符串中检查 prefix 的起始位置。
- end (可选) - 字符串中检查 prefix 的结束位置。
startswith() 返回值
startswith()
方法返回一个布尔值。
- 如果字符串以指定的`prefix`开头,则返回 True。
- 如果字符串不以指定的`prefix`开头,则返回 False。
示例 1: 不带 start 和 end 参数的 startswith()
text = "Python is easy to learn."
result = text.startswith('is easy')
# returns False
print(result)
result = text.startswith('Python is ')
# returns True
print(result)
result = text.startswith('Python is easy to learn.')
# returns True
print(result)
输出
False True True
示例 2: 带 start 和 end 参数的 startswith()
text = "Python programming is easy."
# start parameter: 7
# 'programming is easy.' string is searched
result = text.startswith('programming is', 7)
print(result)
# start: 7, end: 18
# 'programming' string is searched
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'))
# prints True
print(result)
result = text.startswith(('is', 'easy', 'java'))
# prints False
print(result)
# With start and end parameter
# 'is easy' string is checked
result = text.startswith(('programming', 'easy'), 12, 19)
# prints False
print(result)
输出
True False False
如果你需要检查字符串是否以指定的后缀结尾,你可以使用 Python 中的 endswith() 方法。
另请阅读