When doing text processing, you often have to judge whether a text starts with a substring, or ends with a string. Python provides two functions for this purpose:
S.startswith (prefix[, start[, end]), BOOL
Returns True if the string s starts with prefix, otherwise false is returned. Start and end are two parameters that can be defaulted. is the position to begin the comparison and the position to end the comparison. This function can also be written as S[start:end].startswith (prefix).
S.endswith (suffix[, start[, end]), BOOL
If the string s ends with suffix, returns True, the No returns FALSE. Similar to StartsWith, this function can also be written as s[start:end].endswith (suffix). Start and end are still counted from the left.
Do an example:
>>> "Fish". StartsWith ("fi") True>>> "Fish". StartsWith ("fi", 1) False>> > "Fish". EndsWith ("sh") True>>> "Fish". EndsWith ("sh", 3) False
Python's two functions have a special place-its prefix and suffix parameters can be not only strings, but also a tuple. As long as one of them is established, it returns true, that is, a "or" relationship. Like what:
If Filename.endswith (('. gif ', '. jpg ', '. tiff ')):
Print "%s is a picture file"%filename
The above two lines of code determine whether a file is a picture file, depending on if the file name extension is "gif", "JPG", or "tiff". This code can also be written as:
If Filename.endswith (". gif") or Filename.endswith (". jpg") Orfilename.endswith (". Tiff"):
Print "%s is a picture file"%filename
But this is more troublesome. It is important to note that friends who are unfamiliar with python may forget the parentheses around the tuple.
Python's startswith and EndsWith