Python's startswith and EndsWith

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.