The startswith and endswith functions in Python use instances

  • 2020-04-02 14:00:43
  • OfStack

Two functions in Python are the startswith() function and the endswith() function, both of which are very similar. The startswith() function determines whether the text startswith a character, and the endswith() function determines whether the text endswith a character.

Startswith () function

This function determines whether a text begins with one or more characters and returns 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 returns 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

Determines whether the file is an exe execution file

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


# coding=utf8
 
fileName1='qttc.exe'
if(fileName1.endswith('.exe')):
    print ' This is a exe Executable files '  
else:
    print ' This is not a exe Executable files '
 
# Execution result: this is one exe Executable files

Determines if the filename 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 '
    
# Result: this is a picture


Related articles: