Python endswith函数
什么是endswith函数?
endswith() 是Python中的一个字符串方法,用于检查一个字符串是否以指定的后缀字符串结尾。它返回一个布尔值,即如果字符串以指定的后缀结尾,则返回True;否则返回False。
用法示例
下面我们来看一个简单的示例,使用endswith()方法检查一个字符串是否以特定后缀结尾。
str1 = "Hello, world!"
result = str1.endswith("world!")
print(result)
运行以上代码,我们会得到输出结果为:True。
参数说明
endswith()方法可以接受一个或者多个后缀字符串作为参数。它也可以接受可选的start和end参数用于指定要检查的字符串的起始和结束位置。
str1 = "Hello, world!"
result = str1.endswith("world!", 7, 13)
print(result)
运行以上代码,我们会得到输出结果为:False。这是因为我们指定起始和结束位置为7和13,所以endswith()方法只会检查字符串中这部分的内容。
注意事项
- endswith()方法区分大小写,所以后缀字符串必须与要检查的字符串的结尾部分保持完全一致。
str1 = "Hello, world!"
result = str1.endswith("World!")
print(result)
运行以上代码,我们会得到输出结果为:False。
- 如果我们传递一个元组作为参数,则endswith()方法会检查字符串是否以元组中的任意一个后缀结尾,如果是则返回True。否则返回False。
str1 = "Hello, world!"
suffix_tuple = ("world!", "Python")
result = str1.endswith(suffix_tuple)
print(result)
运行以上代码,我们会得到输出结果为:True。因为字符串以元组中的第一个后缀 “world!” 结尾。
小结
在本文中,我们详细讲解了Python中的endswith()方法的用法和参数说明。我们通过示例代码演示了如何使用endswith()方法检查字符串是否以特定后缀结尾,并介绍了一些注意事项。