python中endswith函数怎么使用

38次阅读
没有评论

共计 563 个字符,预计需要花费 2 分钟才能阅读完成。

endswith 函数用于判断字符串是否以指定的后缀结尾,它的使用方法如下:

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

其中,string是要检查的字符串,suffix是要检查的后缀。startend 是可选参数,用于指定要检查的字符串的起始和结束位置。

下面是一些使用示例:

string = "Hello, World!"

# 检查字符串是否以 "World!" 结尾
result = string.endswith("World!")
print(result)  # 输出:True

# 检查字符串是否以 "Hello" 开头
result = string.endswith("Hello")
print(result)  # 输出:False

# 检查字符串中从索引 2 开始的子字符串是否以 "World!" 结尾
result = string.endswith("World!", 2)
print(result)  # 输出:False

# 检查字符串中从索引 2 到索引 13 的子字符串是否以 "World!" 结尾
result = string.endswith("World!", 2, 13)
print(result)  # 输出:True

注意:endswith函数区分大小写。如果要忽略大小写,可以先将字符串转换为小写或大写,然后再进行判断。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-13发表,共计563字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)