欢迎访问宙启技术站
智能推送

Python中如何使用endswith()函数判断字符串是否以指定的后缀结尾

发布时间:2023-07-13 08:51:31

在Python中,可以使用endswith()函数来判断一个字符串是否以指定的后缀结尾。

endswith()函数的语法如下:

string.endswith(suffix[, start[, end]])

其中,suffix是需要判断的后缀字符串,start和end是可选的参数,用于指定需要在字符串中进行判断的起始位置和结束位置。

endswith()函数会返回一个布尔值,如果字符串以指定的后缀结尾,则返回True,否则返回False。

以下是一些使用endswith()函数的示例:

1. 判断字符串是否以指定的后缀结尾:

string = "Hello, World!"
suffix = "World!"

if string.endswith(suffix):
    print("String ends with suffix")
else:
    print("String does not end with suffix")

输出结果为:

String ends with suffix

2. 指定起始位置和结束位置进行判断:

string = "Hello, World!"
suffix = "lo"
start = 2
end = 5

if string.endswith(suffix, start, end):
    print("String ends with suffix")
else:
    print("String does not end with suffix")

输出结果为:

String ends with suffix

在上述示例中,字符串"Hello, World!"以后缀"lo"结尾,且指定的起始位置和结束位置为索引2和索引5,因此判断结果为True。

总结一下,endswith()函数是Python中用于判断一个字符串是否以指定的后缀结尾的函数。通过该函数的灵活运用,可以方便地实现对字符串的后缀进行判断的功能。