SoFunction
Updated on 2024-10-29

Examples of using the startswith and endswith functions in Python

In Python there are two functions are startswith () function and endswith () function, the function are very similar, startswith () function to determine whether the text begins with a certain character, endswith () function to determine whether the text ends with a certain character.

startswith() function

This function determines whether a text begins with a certain character or characters, the result is returned as True or False.

Copy Code The code is as follows.

text='welcome to qttc blog'
print ('w')      # True
print ('wel')    # True
print ('c')      # False
print ('')       # True

endswith() function

This function determines whether a text to a certain character or several characters to the end, the results to True or False return.

Copy Code The code is as follows.

text='welcome to qttc blog'
print ('g')        # True
print ('go')       # False
print ('og')       # True
print ('')         # True
print ('g ')       # False

Determine if a file is an exe executable

We can use the endswith () function to determine the file name is not to the end of the .exe suffix to determine whether it is an executable file

Copy Code The code is as follows.

# coding=utf8
 
fileName1=''
if(('.exe')):
print 'This is an exe executable file'
else:
print 'This is not an exe executable'
 
# Result: this is an exe executable file

Determine if the filename suffix is an image

Copy Code The code is as follows.

# coding=utf8
 
fileName1=''
if ('.gif') or ('.jpg') or ('.png'):
print 'This is a picture'
else:
print 'This is not a picture'
    
# The result of the implementation: this is a picture