在Python中有两个函数分别是startswith()函数与endswith()函数,功能都十分相似,startswith()函数判断文本是否以某个字符开始,endswith()函数判断文本是否以某个字符结束。其返回值为布尔型,为真时返回True,否则返回False。
一、语法结构
以endswith()方法为例:
str.endswith(suffix[, start[, end]])
- suffix — 该参数可以是一个字符串或者是一个元素This could be a string or could also be a tuple of suffixes to look for.
- start — 字符串中的开始位置。
- end — 字符中结束位置。
二、用法
1、startswith()函数
判断一个文本是否以某个或几个字符开始,结果以True或者False返回。
text='welcome to 361way blog' print text.startswith('w') # True print text.startswith('wel') # True print text.startswith('c') # False print text.startswith('') # True
2、endswith()函数
#!/usr/bin/python str = "this is string example....wow!!!" suffix = "wow!!!" print str.endswith(suffix) print str.endswith(suffix,20) suffix = "is" print str.endswith(suffix, 2, 4) print str.endswith(suffix, 2, 6)
三、示例应用
1、判断文件是否为exe执行文件
# coding=utf8 fileName1='361way.exe' if(fileName1.endswith('.exe')): print '这是一个exe执行文件' else: print '这不是一个exe执行文件'
2、判断文件名后缀是否为图片
# coding=utf8 fileName1='pic.jpg' if fileName1.endswith('.gif') or fileName1.endswith('.jpg') or fileName1.endswith('.png'): print '这是一张图片' else: print '这不是一张图片'
注:第四行的判断可以缩写为if filename.endswith((‘.gif’, ‘.jpg’, ‘.png’)): ,效果是一样的。
3、结合OS模块查找当前目录下的所有txt文件
import os items = os.listdir(".") newlist = [] for names in items: if names.endswith(".txt"): newlist.append(names) print newlist