May 10, 2021 Python2
Scene:
Strings that match at the beginning or end are typically used in matching file types or url
Startwith or endwith is generally used
>>> a='http://www.w3cschool.cn/vip'
>>> a.startswith ('http')
True
Note: The parameters in both methods can be str or metagroups, but not lists and dictionaries
>>> a='http://www.w3cschool.cn/vip'
>>> a.startswith (('http','ftp'))
True
If it is a list or dictionary, an error is reported
>>> a='http://www.w3cschool.cn/vip'
>>> a.startswith (['http','ftp'])
Traceback (most recent call last):
File "", line 1, in
a.startswith (['http','ftp'])
TypeError: startswith first arg must be str or a tuple of str, not list
>>>
In fact, in addition to the above method, you can also use snipping to achieve, but the code does not look so good
>>> a='http://www.w3cschool.cn/vip'
>>> a[0:4]=='http'
True
>>>
Of course, we can also do this with regular expressions, but it's a little bit more difficult to understand.
>>> import re
>>> url = 'http://www.python.org'
>>> re.match('http:|https:|ftp:', url)
0, 5), match='http:'>
>>> help(re.match )
Help on function match in module re:
match(pattern, string, flags=0)
Try to apply the pattern at the start of the string, returning
a match object, or None if no match was found.
>>>