Python之line.startswith
line.startswith
是 Python 中的一个字符串方法,用于检查字符串是否以指定的前缀开始。如果是,则返回
True
,否则返回
False
。
例如,如果我们有一个字符串 line = "Hello, world!"
,我们可以使用 line.startswith("Hello")
来检查这个字符串是否以 “Hello” 开始。这将返回 True
。
这个方法是非常有用的,特别是在处理文本文件时,你可能需要检查每一行是否以特定的字符串开始,例如一个特定的注释字符。
下面是一个更具体的例子:
line = "Hello, world!"
if line.startswith("Hello"):
print("The line starts with 'Hello'.")
else:
print("The line does not start with 'Hello'.")
- 1
- 2
- 3
- 4
- 5
- 6
在这个例子中,因为 line
确实以 “Hello” 开始,所以程序将打印 “The line starts with ‘Hello’.”。
评论记录:
回复评论: