Python之line.endswith
文章目录
在Python中,
line.endswith()
是一个字符串方法,用于检查字符串是否以指定的后缀结束。如果字符串以给定的后缀结束,则返回True,否则返回False。
以下是使用line.endswith()
的示例代码:
line = "Hello, world!"
if line.endswith("world!"):
print("The line ends with 'world!'")
else:
print("The line does not end with 'world!'")
在上面的示例中,我们首先定义了一个字符串line
,然后使用line.endswith()
方法检查该字符串是否以"world!“为后缀。如果是,则打印"The line ends with ‘world!’”,否则打印"The line does not end with ‘world!’"。
除了使用字符串作为后缀之外,还可以使用其他类型的数据作为后缀,例如列表或元组。在这种情况下,line.endswith()
方法将检查字符串是否以列表或元组中的任何一个元素为后缀。例如:
line = "Hello, world!"
suffixes = ["world!", "python"]
if line.endswith(suffixes):
print("The line ends with any of the suffixes in the list.")
else:
print("The line does not end with any of the suffixes in the list.")
在上面的示例中,我们定义了一个包含两个字符串的列表suffixes
,然后使用line.endswith()
方法检查该字符串是否以suffixes
列表中的任何一个元素为后缀。如果是,则打印"The line ends with any of the suffixes in the list.“,否则打印"The line does not end with any of the suffixes in the list.”。