SoFunction
Updated on 2024-11-19

For a detailed explanation of python's method of matching the beginning and end of a string

1, you need to check the beginning or end of the string by specifying the text pattern, such as file name suffix, URL Scheme and so on. A simple way to check the beginning or end of a string is to use the () or is () method. For example:

>>> filename = ''
>>> ('.txt')
True
>>> ('file:')
False
>>> url = ''
>>> ('http:')
True
>>> 

2. If you want to check multiple match possibilities, just put all matches into a tuple and pass it to the startswith() or endswith() method:

>>> import os
>>> filenames = ('.')
>>> filenames
[ 'Makefile', '', '', '', '' ]
>>> [name for name in filenames if (('.c', '.h')) ]
['', '', ''
>>> any(('.py') for name in filenames)
True
>>>
 
# Example 2
from  import urlopen
def read_data(name):
 if (('http:', 'https:', 'ftp:')):
 return urlopen(name).read()
 else:
 with open(name) as f:
  return () 

Oddly enough, a tuple must be entered as a parameter in this method. If you happen to have a selector of type list or set, be sure to call tuple() to convert it to a tuple type before passing the parameter. For example:

>>> choices = ['http:', 'ftp:']
>>> url = ''
>>> (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
>>> (tuple(choices))
True
>>>

3, startswith () and endswith () methods provide a very convenient way to do the string beginning and end of the check. Similar operations can be achieved using slices, but the code does not look as elegant. For example:

>>> filename = ''
>>> filename[-4:] == '.txt'
True
>>> url = ''
>>> url[:5] == 'http:' or url[:6] == 'https:' or url[:4] == 'ftp:'
True
>>>

4, you can can also want to use regular expressions to achieve, for example:

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

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

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

Above this on python match the beginning and end of the string method details is all I share with you, I hope to give you a reference, and I hope you support me more.