栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python中的startswith和endswith函数使用实例

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python中的startswith和endswith函数使用实例

在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 '这不是一张图片'
    
# 执行结果:这是一张图片

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/36065.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号