Python 中的 startswith() 方法是一个字符串方法,用于检查字符串是否以指定的前缀开头。如果字符串以指定的前缀开头,则返回 True,否则返回 False。
参数值
| 参数 | 说明 |
|---|---|
| prefix |
|
| start |
|
| end |
|
返回值
Python 中的 startswith() 方法返回一个 bool(True 或 False)。
如何在 Python 中使用 startswith()
示例 1
startswith() 方法检查字符串是否以指定的子字符串开头。如果字符串以给定的子字符串开头,则返回 True,否则返回 False。
text = 'Hello, World!'
print(text.startswith('Hello'))
示例 2
该方法区分大小写,因此“H”与“h”不同。
text = 'Hello, World!'
print(text.startswith('hello'))
示例 3
您可以指定字符串中应开始检查的起始索引。
text = 'Hello, World!'
print(text.startswith('World', 7)