简单方法:
使用 str.startswith() , str.endswith()
In [32]: filename='span.txt'
In [33]: filename.startswith('sp')
Out[33]: True
In [34]: filename.endswith('xt')
Out[34]: True
同事针对多个选项做检查,给两个函数提供包含可能选项的元组即可:
In [35]: import os
In [36]: filenames = os.listdir('.')
In [37]: filenames
Out[37]:
['.accelerate',
'desktop.ini',
'PyCharmProjects',
'Python Scripts',
'Tencent Files']
In [38]: [name for name in filenames if name.endswith(('.ini','e'))]
Out[38]: ['.accelerate', 'desktop.ini']
In [39]: any(name.endswith('.ini') for name in filenames)
Out[39]: True
如果刚好把选项指定在了 list 或 set 内,首先使用 tuple() 将他们转换成 tuple():
In [40]: choices = ['http:','ftp:']
In [41]: url='http://baidu.com'
In [42]: url.startswith(choices)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-42-618fcafc4cd7> in <module>()
----> 1 url.startswith(choices)
TypeError: startswith first arg must be str or a tuple of str, not list
In [43]: url.startswith(tuple(choices))
Out[43]: True