"Python Cookbook" "String and Text" 2. Text match at the beginning or end of a string

Source: Internet
Author: User

Problem: Check the specified text pattern at the beginning or end of the string, such as checking the file extension, URL protocol type, etc.;

Workaround: Use the Str.startswith () and Str.endswith () methods

>>> filename='Spam.txt'>>> Filename.endswith ('. txt') True>>> Filename.startswith ('File:') False>>> url='http://www.python.org'>>> Url.startswith ('Htto:') False>>> Url.startswith ('http:') True>>>

If you are checking for multiple options at the same time, simply give the function startswith () and Str.endswith () a tuple with multiple possible options:

>>>ImportOs>>>OS.GETCWD ()‘D:\\4autotests\\02script\\pythonbase' >>>Os.listdir () [‘foo.py‘,‘Hello.txt‘,‘Makefile‘,‘Spam.c‘,‘Spam.h‘,‘test1.py‘]>>> filename=Os.listdir () >>>filename[‘foo.py‘,‘Hello.txt‘,‘Makefile‘,‘Spam.c‘,‘Spam.h‘,‘test1.py‘]>>> [Namefor name in filename if Name.endswith ( ' .c "  ' .h  ' spam.c ' .py  ") for name in filename) True                 

Finally, the StartsWith () and Str.endswith () methods work well when combined with other operations, such as common data grooming operations. For example, the following statement checks that there are no specific files in the directory:

>>>OS.GETCWD ()'D:\\4autotests\\02script\\pythonbase'>>>Os.listdir () ['foo.py','Hello.txt','Makefile','SPAM.C','spam.h','test1.py']>>>ifAny (Name.endswith ('. txt','. PY')) forNameinchOs.listdir (OS.GETCWD ())):Print('File exists') file exists>>>

"Python Cookbook" "String and Text" 2. Text match at the beginning or end of a string

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.