Python字符串结尾

Python字符串结尾教程

在开发过程中,很多时候我们需要判断一个 字符串 是否以某个字符或者是否以某个字符串结束的需求,在 Python 中,判断某个字符串是否以某个字符或者是否以某个字符串结尾的函数为 endswith() 。

Python endswith()函数详解

语法

S.endswith(suffix[, start[, end]]) -> bool

参数

参数 描述
s 表示原字符串。
suffix 要检索的子串。
start 指定检索结束的起始位置索引,如果不指定,则默认从头结束检索。
end 表示结束检索的结束位置。如果不指定,则默认一直检索到结尾。

返回值

用于检索字符串是否以指定字符串结尾,如果是返回 True;反之返回 False。

案例

以指定字符串结束

使用 endswith() 函数,判断以指定字符串结束,返回 True

print("嗨客网(www.haicoder.net)") # 使用 endswith() 函数,判断以指定字符串结束,返回 True strHaicoder = "I study Python From HaiCoder" print("IsEnd =", strHaicoder.endswith("HaiCoder"))

程序运行后,控制台输出如下:

33 python字符串结束.png

首先,我们定义了一个字符串类型的 变量 strHaicoder,接着我们使用字符串的 endswith() 函数判断变量 strHaicoder 是否以字符串 “HaiCoder” 结束,结果返回 True。

不以指定字符串结束

使用 endswith() 函数,判断不以指定字符串结束,返回 Fasle

print("嗨客网(www.haicoder.net)") # 使用 endswith() 函数,判断不以指定字符串结束,返回 False strHaicoder = "I study Python From HaiCoder" print("IsEnd =", strHaicoder.endswith("Python"))

程序运行后,控制台输出如下:

34 python字符串结束.png

首先,我们定义了一个字符串类型的变量 strHaicoder,接着我们使用字符串的 endswith() 函数判断变量 strHaicoder 是否以字符串 “Python” 结束,结果返回 False。

Python字符串结尾总结

在 Python 中,判断某个字符串是否以某个字符或者是否以某个字符串结尾的函数为 endswith() 。Python endswith() 函数语法:

S.endswith(prefix[, start[, end]]) -> bool