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