Python startswith () function and endswith function, startswithendswith
Function: startswith ()
Purpose: Determine whether a string starts with a specified character or substring.
I. Function Description
Syntax: string. startswith (str, beg = 0, end = len (string ))
Or string [beg: end]. startswith (str)
Parameter description:
String: the string to be detected.
Str: the specified character or substring. (You can use tuples to match them one by one)
Beg: Set the start position of string detection (optional)
End: set the end position of string detection (optional)
If the beg and end parameters exist, check in the specified range; otherwise, check in the entire string.
Return Value
If a string is detected, True is returned; otherwise, False is returned. The default null character is True.
Function parsing: If the string starts with str, True is returned; otherwise, False is returned.
Ii. Instances
>>> S = 'Hello good boy doiido '>>> print s. startswith ('H') True >>> print s. startswith ('hel') True >>> print s. startswith ('h', 4) False >>> print s. startswith ('Go', 6, 8) True # match an empty Character Set >>> print s. startswith ('') True # matched tuples >>> print s. startswith ('T', 'B', 'H') True
Environment: used for if judgment
>>> if s.startswith('hel'): print "you are right"else: print "you are wrang"you are right
Function: endswith ()
Function: determines whether a string ends with a specified character or substring. It is often used to determine the file type.
I. Function Description
Syntax: string. endswith (str, beg = [0, end = len (string)])
String [beg: end]. endswith (str)
Parameter description:
String: the string to be detected.
Str: specified character or substring (tuples can be used to match each character)
Beg: Set the start position of string detection (optional, starting from the left)
End: set the end position of string detection (optional, starting from the left)
If the beg and end parameters exist, check in the specified range; otherwise, check in the entire string.
Return Value:
If a string is detected, True is returned; otherwise, False is returned.
Resolution: If the string ends with str, True is returned; otherwise, False is returned.
Note: NULL characters are considered true.
Ii. Instances
>>> S = 'Hello good boy doiido '>>> print s. endswith ('O') True >>> print s. endswith ('id') True >>> print s. endswith ('Do ', 4) True >>> print s. endswith ('Do ',) False # match NULL Character Set >>> print s. endswith ('') True # match tuples >>> print s. endswith ('T', 'B', 'O') True
Common Environment: used to determine the file type (comparison, executable files)
>>> f = 'pic.jpg' >>> if f.endswith(('.gif','.jpg','.png')): print '%s is a pic' %f else: print '%s is not a pic' %f pic.jpg is a pic
The Python startswith () function and endswith function are all shared with you in this article. I hope to give you a reference and support for the help house.