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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Regarding the problem of removing the Python interpreter that comes with Linux systems, many Linux distributions will preinstall the Python interpreter when installed, and it does not use the package manager...

Pylance type detection problem solution when using custom decorator In Python programming, decorator is a powerful tool that can be used to add rows...

About Pythonasyncio...

Using python in Linux terminal...

Loading pickle file in Python 3.6 environment error: ModuleNotFoundError:Nomodulenamed...

Compatibility issues between Python asynchronous libraries In Python, asynchronous programming has become the process of high concurrency and I/O...

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

The problem and solution of the child process continuing to run when using signals to kill the parent process. In Python programming, after killing the parent process through signals, the child process still...
