Python: String beginning or ending match str.startswith (), Str.endswith ()

Source: Internet
Author: User

Problem

You need to check the beginning or end of the string with the specified text pattern, such as the filename suffix, urlscheme, and so on.


Solution Solutions


1. An easy way to check the beginning or end of a string is to use the Str.startswith () or the Str.endswith () method. Like what:

EG1:
>>> filename = ' spam.txt '
Span style= "font-size:12px" >>>> filename.endswith ('. txt ')
True
>>> filename.startswith (' File: ')
false
>>> url = ' http://www.python.org '
>>> url.startswith (' http: ')
True

If you want to check for multiple matches, just put all the matches into a tuple and pass it to StartsWith () or EndsWith () Method:

EG2:
>>> Import OS
>>> filenames = Os.listdir ('. ')
>>> filenames
[' Makefile ', ' foo.c ', ' bar.py ', ' spam.c ', ' spam.h ']
>>> [name for name in filenames if Name.endswith (('. C ', '. h ')]
[' foo.c ', ' spam.c ', ' spam.h '
>>> any (Name.endswith ('. Py ') for name in filenames)
True
>>>


Here is another example:

EG3:
From urllib.request import Urlopen
def read_data (name):
if Name.startswith (' http: ', ' https: ', ' ftp: ')):
return Urlopen (name). Read ()
Else:
With open (name) as F:
return F.read ()
Strangely, you must enter a tuple as a parameter in this method. If you happen to have a list orto ensure that a tuple () is called before the parameter is passed to the tuple type, by selecting the set type. For example:
>>> choices = [' http: ', ' ftp: ']
>>> url = ' http://www.python.org '
>>> Url.startswith (choices)
Traceback (most recent):
File "<stdin>", line 1, in <module>
Typeerror:startswith First arg must be str or a tuple of STR, not list
>>> Url.startswith (tuple (choices))
True
>>>

The startswith () and EndsWith () methods provide a very convenient way to do the beginning of a string andend of the check.

2. Similar operations can also be done using slices, but the code does not look so elegant.


eg
>>> filename = ' spam.txt '
>>> filename[-4:] = = '. txt '
True
>>> url = ' http://www.python.org '
>>> Url[:5] = = ' http: ' or url[:6] = = ' https: ' or url[:4] = = ' ftp: '
True
>>>

3. you can also want to use regular expressions to implement,

eg
>>> Import re
>>> url = ' http://www.python.org '
>>> Re.match (' http:jhttps:jftp: ', url)
<_sre. Sre_match Object at 0x101253098>
>>>
This is a good way to do it, but for a simple match it's a little bit bigger, and the methods in this section are more simple and run faster.


Finally, when combined with other operations such as general data aggregation, StartsWith () and the EndsWith () method is very good. For example, the following statement checks whether a specified file type exists in a folder :
If any (Name.endswith (". C ', '. h ')) for name in Listdir (dirname)):

Python: String beginning or ending match str.startswith (), Str.endswith ()

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.