函数记忆 : startswith() 与 endswith

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


参数说明:
string:  被检测的字符串
str:      指定的字符或者子字符串。(可以使用元组,会逐一匹配)
beg:    设置字符串检测的起始位置(可选)
end:    设置字符串检测的结束位置(可选)
如果存在参数 beg 和 end,则在指定范围内检查,否则在整个字符串中检查
返回值
如果检测到字符串,则返回True,否则返回False。默认空字符为True
函数解析:如果字符串string是以str开始,则返回True,否则返回False

实例:if判断

-------------------------------------------------------------------------------------

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

参数说明:
string:  被检测的字符串
str:      指定的字符或者子字符串。(可以使用元组,会逐一匹配)
beg:    设置字符串检测的起始位置(可选)
end:    设置字符串检测的结束位置(可选)
如果存在参数 beg 和 end,则在指定范围内检查,否则在整个字符串中检查
返回值
如果检测到字符串,则返回True,否则返回False。默认空字符为True
函数解析:如果字符串string是以str结束,则返回True,否则返回False

实例:用于判断文件类型(比如图片,可执行文件)

f = 'pic.jpg' 
if f.endswith(('.gif','.jpg','.png')): 
    print '%s is a pic' %f 
else: 
    print '%s is not a pic' %f 
   
#结果   
pic.jpg is a pic 
原文地址:https://www.cnblogs.com/CNHK1949/p/10467542.html