There are two functions in Python, namely startswith () function and endswith () function, which are very similar in function. The startswith () function determines whether the text starts with a certain character, and the endswith () function determines whether the text ends with a certain character.
startswith () function
This function determines whether a text starts with a character or characters, and the result is returned as True or 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 () function
This function determines whether a text ends with one or more characters, and the result is returned as True or 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
Determine whether the file is an exe executable file
We can use the endswith () function to determine whether the file name ends with an .exe suffix to determine whether it is an executable file
# coding = utf8
fileName1 = 'qttc.exe'
if (fileName1.endswith ('. exe')):
print 'this is an exe execution file'
else:
print 'this is not an exe execution file'
# execution result: this is An exe execution file
Determine whether the file name suffix is a picture
# coding = utf8
fileName1 = 'pic.jpg'
if fileName1.endswith ('. gif') or fileName1.endswith ('. jpg') or fileName1.endswith ('. png'):
print 'This is a picture'
else:
print 'This is not a picture'
# Execution result: this is a picture