This article focuses on Python Cookbook (string and text) for text-matching operations at the beginning or end of a string, involving Python using Str.startswith () and Str.endswith () Method for the start or end of a string specific text matching operation related implementation tips, the need for friends can refer to the following
This article describes Python's text-matching operations at the beginning or end of a string. Share to everyone for your reference, as follows:
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 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 startswith()
the function and str.endswith()
provide a tuple with multiple possible options:
>>> import os>>> 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 ']>>> [name for name in filename if name . EndsWith (('. C ', '. h ')] [' spam.c ', ' spam.h ']>>> any (Name.endswith ('. Py ') for name in filename) True
Finally, it startswith()
str.endswith()
works well when combined with methods and 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 ']>>> if any (Name.endswith (('. txt ', '. Py ')) for name in Os.listdir ( OS.GETCWD ()): print (' file exists ') file exists >>>
(Code from "Python Cookbook")