Method
str.startswith()
str,endswith()
Discussion
检查字符串首尾的简单方法
>>> filename = 'spam.txt'
>>> filename.endswith('.txt')
True
>>> filename.startswith('file:')
False
>>> url = 'http://www.python.org'
>>> url.startswith('http:')
True
>>>
检查多个字段
>>> 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
>>>
Function | Description |
---|---|
os.listdir(path) | 返回path下文件目录的列表 |
any(obj) | 或逻辑。判断obj是否为空对象,如果都为空、0、false,则返回false,如果不都为空、0、false,则返回true。 |
all(obj) | 与逻辑。obj对象的所有元素不为0、”、False或者x为空对象,则返回True,否则返回False |
另一个例子
from urllib.request import urlopen
def read_data(name):
#name可能是网页地址或是本地文件地址
if name.startswith(('http:', 'https:', 'ftp:')):
return urlopen(name).read()
else:
with open(name) as f:
return f.read()
输入必须为tuple
>>> 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
>>>
利用切片、正则表达式的前缀后缀检查
>>> filename = 'spam.txt'
>>> filename[-4:] == '.txt'
True
>>> url = 'http://www.python.org'
>>> url[:5] == 'http:' or url[:6] == 'https:' or url[:4] == 'ftp:'
True
>>>
>>> import re
>>> url = 'http://www.python.org'
>>> re.match('http:|https:|ftp:', url)
<_sre.SRE_Match object at 0x101253098>
>>>
对于简单的匹配或检查问题,str.startswith()
和str.endswith()
更为简单且更具可读性