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

使用Python的StringEnd()函数检查字符串是否以特定后缀结尾的例子

发布时间:2023-12-24 08:44:17

在Python中,可以使用字符串对象的endswith()方法来检查字符串是否以特定后缀结尾。endswith(suffix)接受一个字符串参数suffix,如果字符串以suffix结尾,则返回True;否则返回False。

下面是一个使用endswith()函数的示例代码:

def check_suffix(string, suffix):
    if string.endswith(suffix):
        return True
    else:
        return False

# 示例用法
string1 = "Hello, world!"
suffix1 = "!"
print(check_suffix(string1, suffix1))  # True

string2 = "Hello, world!"
suffix2 = "o"
print(check_suffix(string2, suffix2))  # False

string3 = "Hello, world!"
suffix3 = "world!"
print(check_suffix(string3, suffix3))  # True

在这个例子中,我们定义了一个check_suffix()函数,它接受两个参数:一个字符串和一个后缀。函数内部使用endswith()方法来检查字符串是否以指定的后缀结尾。如果是,则返回True;否则返回False。

在示例用法中,我们分别传入不同的字符串和后缀来测试check_suffix()函数的功能。 个示例中,字符串"Hello, world!"以后缀"!"结尾,因此返回True。第二个示例中,后缀"o"不是字符串"Hello, world!"的结尾,因此返回False。第三个示例中,后缀"world!"正好是字符串"Hello, world!"的结尾,因此返回True。

需要注意的是,endswith()方法还可以接收一个可选的start和end参数,用于指定检查的字符串范围。例如,string.endswith(suffix, start, end)会检查字符串string[start:end]是否以suffix结尾。如果未提供start和end参数,则默认检查整个字符串。