当前位置:网站首页>《Python Cookbook 3rd》笔记(2.2):字符串开头或结尾匹配
《Python Cookbook 3rd》笔记(2.2):字符串开头或结尾匹配
2020-11-09 23:53:00 【巨輪】
字符串开头或结尾匹配
问题
你需要通过指定的文本模式去检查字符串的开头或者结尾,比如文件名后缀, URL Scheme 等等。
解法
检查字符串开头或结尾的一个简单方法是使用 str.startswith() 或者是str.endswith() 方法。比如:
>>> filename = 'spam.txt'
>>> filename.endswith('.txt')
True
>>> filename.startswith('file:')
False
>>> url = 'http://www.python.org'
>>> url.startswith('http:')
True
>>>
如果你想检查多种匹配可能,只需要将所有的匹配项放入到一个元组中去,然后传给 startswith() 或者 endswith() 方法:
>>> 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
>>>
另一个例子
from urllib.request import urlopen
def read_data(name):
if name.startswith(('http:', 'https:', 'ftp:')):
return urlopen(name).read()
else:
with open(name) as f:
return f.read()
奇怪的是,这个方法中必须要输入一个元组作为参数。如果你恰巧有一个 list 或者 set 类型的选择项,要确保传递参数前先调用 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
>>>
讨论
startswith() 和 endswith() 方法提供了一个非常方便的方式去做字符串开头和结尾的检查。类似的操作也可以使用切片来实现,但是代码看起来没有那么优雅。比如:
>>> 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:jhttps:jftp:', url)
<_sre.SRE_Match object at 0x101253098>
>>>
这种方式也行,但是对于简单的匹配实在是有点杀鸡用牛刀了,本节中的方法更加简洁。
最后提一下,当和其他操作比如普通数据聚合相结合的时候 startswith() 和 endswith() 方法是很不错的。比如,下面这个语句检查某个文件夹中是否存在指定的文件类型:
if any(name.endswith(('.c', '.h')) for name in listdir(dirname)):
...
版权声明
本文为[巨輪]所创,转载请带上原文链接,感谢
https://my.oschina.net/jallenkwong/blog/4710364
边栏推荐
- Python prompt attributeerror or depreciation warning: This module was degraded solution
- SQL intercepts the data before and after the '.'
- 2020-11-09:谈谈布隆过滤器和布谷鸟过滤器的相同点和不同点?
- Error running app:Default Activity not found 解决方法
- “wget: 无法解析主机地址”的解决方法
- CUDA_ Register and local memory
- Algorithm template arrangement (1)
- 消防知识线上答题活动小程序复盘
- 利用尾巴作为时间序列进行处理来识别鲸鱼
- The problem of looting by leetcode
猜你喜欢

z-index属性详解

面试官:缓存穿透、缓存雪崩和缓存击穿是什么?

November 09, 2020: talk about the similarities and differences between the bulon filter and the cuckoo filter?

How SSL certificate and public IP address affect SEO

DB engines database ranking in November: PostgreSQL holds the top spot in the same period

接缝雕刻算法:一种看似不可能的图像大小调整方法

Top 5 Chinese cloud manufacturers in 2018: Alibaba cloud, Tencent cloud, AWS, telecom, Unicom

day85:luffy:购物车根据有效期不同切换价格&购物车删除操作&价格结算&订单页面前戏

一幅图像能顶16x16字!——用于大规模图像缩放识别的变压器(对ICLR 2021年论文的简要回顾)

Unity使用transform.Rotate进行三维旋转角度出现偏差
随机推荐
Make a home page
Incomplete Polyfill of proxy
剑指offer之打印超过数组一半的数字
C / C + + Programming Notes: C language development tank war! In memory of our lost little overlord game
没有磁盘空间 No space left on device
C++ exception implementation mechanism
Postman (1) -- function introduction
jt-day10
【LeetCode】 92 整数反转
IP address SSL certificate
CRM系统能帮助企业做哪些事?
CUDA常用概念及注意点
C++异常实现机制
Guest interview: Wang Jian
ERP的权限管理的操作与设计--开源软件诞生24
Top 5 Chinese cloud manufacturers in 2018: Alibaba cloud, Tencent cloud, AWS, telecom, Unicom
2018中国云厂商TOP5:阿里云、腾讯云、AWS、电信、联通 ...
The problem of looting by leetcode
爱康国宾怒斥国信证券报告失实,已发律师函
day85:luffy:购物车根据有效期不同切换价格&购物车删除操作&价格结算&订单页面前戏