Python startswith函数与endswith函数使用介绍

函数:startswith()

作用:判断字符串是否以指定字符或子字符串开头

一、函数说明

语法:

string.startswith(str, beg=0,end=len(string))
或
string[beg:end].startswith(str)

参数说明:

string:  被检测的字符串
str:      指定的字符或者子字符串。(可以使用元组,会逐一匹配)
beg:    设置字符串检测的起始位置(可选)
end:    设置字符串检测的结束位置(可选)

如果存在参数 beg 和 end,则在指定范围内检查,否则在整个字符串中检查

返回值

如果检测到字符串,则返回True,否则返回False。默认空字符为True

函数解析:如果字符串string是以str开始,则返回True,否则返回False

我们来看看例子

name = "sulao notebook"
print(name.startswith('su'))
print(name.startswith('lao'))
print(name.startswith('lao', 2))
print(name.startswith('note', 6, 10))

打印的结果

微信截图_20190117102113.jpg

我们看到如上图,需要介绍的是beg参数和end参数,beg参数第一位是0,然后是end参数应该是整个你要匹配的范围+1

同时我们还可以匹配元祖

name.startswith(('s','u','k'))

匹配元祖这个我感觉和endswith没差别了

例如我们来看endswith的例子,和上面一样都能匹配True

name.endswith(('s','u','k'))


函数:endswith()

作用:判断字符串是否以指定字符或子字符串结尾,常用于判断文件类型

一、函数说明

语法:

string.endswith(str, beg=[0,end=len(string)])
string[beg:end].endswith(str)

参数说明:

string: 被检测的字符串
str:      指定的字符或者子字符串(可以使用元组,会逐一匹配)
beg:    设置字符串检测的起始位置(可选,从左数起)
end:    设置字符串检测的结束位置(可选,从左数起)

如果存在参数 beg 和 end,则在指定范围内检查,否则在整个字符串中检查  

返回值:

如果检测到字符串,则返回True,否则返回False。

解析:如果字符串string是以str结束,则返回True,否则返回False

注:会认为空字符为真

我们来看例子

name = "sulao notebook"
print(name.endswith('book'))
print(name.endswith('lao'))
print(name.endswith('book', 10))
print(name.endswith('note', 6, 10))

微信截图_20190117103335.jpg

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://sulao.cn/post/634.html

我要评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。