python matches the beginning and end of a string in detail

  • 2021-01-06 00:39:50
  • OfStack

1. You need to check the beginning or end of the string by specifying the text mode, such as the filename suffix, URL, Scheme, etc. A simple and simple way to check the beginning or end of a string is to use the str.startswith() or str.endswith() method. Such as:


>>> filename = 'spam.txt'
>>> filename.endswith('.txt')
True
>>> filename.startswith('file:')
False
>>> url = 'http://www.python.org'
>>> url.startswith('http:')
True
>>> 

2. If you want to check for multiple matching possibilities, just put all the matches into one tuple and pass them to the startswith() or endswith() methods:


>>> 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
>>>
 
# The sample 2
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() 

Oddly enough, this method has to have one tuple as an argument. If you happen to have an option of type list or set, be sure to call tuple() to convert the argument to a tuple type before passing it. Such as:


>>> choices = ['http:', 'ftp:']
>>> url = 'http://www.python.org'
>>> url.startswith(choices)
Traceback (most recent call last):
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
>>>

3. The startswith() and endswith() methods provide a very convenient way to check the beginning and end of a string. Similar operations can be done using slicing, but the code looks less elegant. Such as:


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

4. You can also want to use regular expressions, such as:


>>> import re
>>> url = 'http://www.python.org'
>>> re.match('http:jhttps:jftp:', url)
<_sre.SRE_Match object at 0x101253098>
>>>

5. The startswith() and endswith() methods are good when combined with other operations such as general data aggregation. For example, the following statement checks to see if the specified file type exists in a folder:


if any(name.endswith(('.c', '.h')) for name in listdir(dirname)):
...

Related articles: