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

yipeiwu_com5年前Python基础

在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中heapq模块的用法

详解Python中heapq模块的用法

heapq 模块提供了堆算法。heapq是一种子节点和父节点排序的树形数据结构。这个模块提供heap[k] <= heap[2*k+1] and heap[k] <= hea...

python如何生成网页验证码

本文实例为大家分享了python生成网页验证码的具体代码,供大家参考,具体内容如下 验证码为pil模块生成,可直接应用于django框架当中。 首先需要安装Pillow模块 我们这里使用...

Python编程中对文件和存储器的读写示例

1.文件的写入和读取 #!/usr/bin/python # -*- coding: utf-8 -*- # Filename: using_file.py # 文件是创建和读...

python实现移位加密和解密

python实现移位加密和解密

本文实例为大家分享了python实现移位加密和解密的具体代码,供大家参考,具体内容如下 代码很简单,就不多做解释啦。主要思路是将字符串转为Ascii码,将大小写字母分别移位密钥表示的位...

简单的通用表达式求10乘阶示例

复制代码 代码如下:(lambda x: lambda n: x(x)(n))(lambda f: lambda n: 1 if n == 0 else n*f(f)(n-1))(10)...