Python字符串开头或末尾匹配

in 互联网技术 with 0 comment  访问: 3,348 次

当你需要通过指定的文本模式去检查字符串的开头或者结尾的时候,比如文件名后缀,URL Scheme等等。

检查字符串开头或结尾的一个简单方法是使用str.startswith()或者是str.endswith()方法, 案例如下:

>>> pyfile = 'printf.py'
>>> pyfile.endswith('.py')
True
>>> pyfile.startswith('printf.')
True
>>> down_url = 'https://fashengba.com'
>>> down_url.startswith('https://')
True

从之前的文章Python数据类型之字符串
中介绍startswitchendswitch的源码中可知这两方法是是支持tuple类型的,所以如果你想检查多种匹配可能,只需要将所有的匹配项放入到一个元组中去, 然后传给startswith()或者endswith()方法中即可,案例如下:

>>> import os
>>> file_names = os.listdir('.')
>>> file_names
['.DS_Store', 'view.txt', 'sshlogin.sh', 'domain_search.py', 'scheduling.php']
>>> [ name for name in file_names if name.endswith(('.sh', '.py', '.php')) ]
['sshlogin.sh', 'domain_search.py', 'scheduling.php']
>>> any((name.endswith('py') for name in file_names))
True

any(iterable)说明:参数iterable, 可迭代对象;如果当iterable所有的值都是0、''或False时,那么结果为False,如果所有元素中有一个值非0、''或False,那么结果就为True

如上可知如果需要利用startswith()或者endswith()方法,这个方法中必须要输入一个元组作为参数。 如果你恰巧有一个list或者set类型的选择项, 要确保传递参数前先调用tuple()将其转换为元组类型, 才能正常运行,示例如下:

>>> suffix = ['http:', 'https:', 'ftp:']
>>> url = 'https://fashengba.com'
>>> url.startswith(suffix)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    url.startswith(suffix)
TypeError: startswith first arg must be str or a tuple of str, not list
>>> url.startswith(tuple(suffix))
True

startswith()endswith() 方法提供了一个非常方便的方式去做字符串开头和结尾的检查。 类似的操作也可以使用切片来实现,虽然代码看起来没有那么优雅, 示例如下:

>>> file_name = 'hello.py'
>>> file_name[-3:] == '.py'
True
>>> blog_url = 'https://fashengba.com'
>>> blog_url[:5] == 'http:' or blog_url[:6] == 'https:' or blog_url[:4] == 'ftp:'
True

当然你还可以使用正则表达式去实现,比如:

>>> import re
>>> blog_url = 'https://fashengba.com'
>>> re.match('http:|https:|ftp:', blog_url)
<_sre.SRE_Match object; span=(0, 6), match='https:'>
>>> 
>>> print('match success') if re.match('http:|https:|ftp:', blog_url) else print('match failed')
match success

这种方式也行得通,但是对于这种简单的匹配实在是有点小材大用了,so,用startswith()或者endswith()方法更加简单并且运行会更快些。

最后提一下,当和其他操作比如普通数据聚合相结合的时候 startswith() 和 endswith() 方法是很不错的。 比如,下面这个语句检查某个文件夹中是否存在指定的文件类型:

>>> from os import listdir
>>> if any(name.endswith(('.txt', '.sh')) for name in listdir('.')):
...     print('ok')
...     
... 
ok
WeZan