Python中的startswith和endswith函数使用实例
作者:junjie 时间:2022-06-19 00:47:55
在Python中有两个函数分别是startswith()函数与endswith()函数,功能都十分相似,startswith()函数判断文本是否以某个字符开始,endswith()函数判断文本是否以某个字符结束。
startswith()函数
此函数判断一个文本是否以某个或几个字符开始,结果以True或者False返回。
text='welcome to qttc blog'
print text.startswith('w') # True
print text.startswith('wel') # True
print text.startswith('c') # False
print text.startswith('') # True
endswith()函数
此函数判断一个文本是否以某个或几个字符结束,结果以True或者False返回。
text='welcome to qttc blog'
print text.endswith('g') # True
print text.endswith('go') # False
print text.endswith('og') # True
print text.endswith('') # True
print text.endswith('g ') # False
判断文件是否为exe执行文件
我们可以利用endswith()函数判断文件名的是不是以.exe后缀结尾判断是否为可执行文件
# coding=utf8
fileName1='qttc.exe'
if(fileName1.endswith('.exe')):
print '这是一个exe执行文件'
else:
print '这不是一个exe执行文件'
# 执行结果:这是一个exe执行文件
判断文件名后缀是否为图片
# coding=utf8
fileName1='pic.jpg'
if fileName1.endswith('.gif') or fileName1.endswith('.jpg') or fileName1.endswith('.png'):
print '这是一张图片'
else:
print '这不是一张图片'
# 执行结果:这是一张图片
标签:Python,startswith,endswith,函数
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python logging设置level失败的解决方法
2022-03-23 13:54:40
Python的dict字典结构操作方法学习笔记
2022-10-27 10:56:21
MySQL数据库的授权原则
2008-12-29 13:39:00
SQL“多字段模糊匹配关键字查询”
2008-04-24 14:16:00
Django中URL视图函数的一些高级概念介绍
2021-04-14 13:35:21
Python调用.NET库的方法步骤
2022-07-02 06:46:17
Python类绑定方法及非绑定方法实例解析
2022-08-10 11:36:38
Python Pillow Image Invert
2023-10-02 12:33:30
django序列化serializers过程解析
2022-09-26 22:22:36
Pycharm及python安装详细步骤及PyCharm配置整理(推荐)
2021-03-15 21:55:51
![](https://img.aspxhome.com/file/2023/9/76019_0s.jpg)
Python中的并发编程asyncio库入门使用
2021-02-13 05:03:52
ASP判断一个字符串中只包含字母和数字
2008-08-08 12:12:00
python解析库Beautiful Soup安装的详细步骤
2023-06-23 04:29:21
![](https://img.aspxhome.com/file/2023/4/92094_0s.png)
对numpy中向量式三目运算符详解
2023-06-28 02:14:55
python numpy--数组的组合和分割实例
2023-02-17 03:58:39
![](https://img.aspxhome.com/file/2023/2/87942_0s.jpg)
python OpenCV学习笔记实现二维直方图
2021-08-17 11:23:49
![](https://img.aspxhome.com/file/2023/3/87963_0s.jpg)
FCKeditor 编辑器实战技巧 Ⅰ
2008-10-08 10:22:00
![](https://img.aspxhome.com/file/uploadpic/20071/200713110656772.gif)
如何将自己的python代码发布在pip install给别人使用你知道吗
2022-07-19 20:36:21
![](https://img.aspxhome.com/file/2023/5/75195_0s.png)
python之如何查找多层嵌套字典的值
2021-12-05 08:57:07
Python爬取OPGG上英雄联盟英雄胜率及选取率信息的操作
2023-12-01 07:06:05
![](https://img.aspxhome.com/file/2023/1/82791_0s.jpg)