当前位置:网站首页>Notes on Python cookbook 3rd (2.2): String start or end match
Notes on Python cookbook 3rd (2.2): String start or end match
2020-11-09 23:53:00 【Giant ship】
String start or end match
problem
You need to check the beginning or end of a string through the specified text pattern , For example, file name suffix , URL Scheme wait .
solution
A simple way to check the beginning or end of a string is to use str.startswith() Or is it str.endswith() Method . such as :
>>> filename = 'spam.txt'
>>> filename.endswith('.txt')
True
>>> filename.startswith('file:')
False
>>> url = 'http://www.python.org'
>>> url.startswith('http:')
True
>>>
If you want to check multiple matches, maybe , Just put all the matches in a tuple , Then pass it to startswith() perhaps endswith() Method :
>>> 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
>>>
Another example
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()
Strangely enough , In this method, a tuple must be entered as a parameter . If you happen to have one list perhaps set Type options , Be sure to call... Before passing parameters tuple() Convert it to a tuple type . such as :
>>> 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
>>>
Discuss
startswith() and endswith() Method provides a very convenient way to check the beginning and end of a string . Similar operations can also be implemented using slices , But the code doesn't look that elegant . such as :
>>> filename = 'spam.txt'
>>> filename[-4:] == '.txt'
True
>>> url = 'http://www.python.org'
>>> url[:5] == 'http:' or url[:6] == 'https:' or url[:4] == 'ftp:'
True
>>>
You can also want to use regular expressions to implement , such as :
>>> import re
>>> url = 'http://www.python.org'
>>> re.match('http:jhttps:jftp:', url)
<_sre.SRE_Match object at 0x101253098>
>>>
This way will work , But for a simple match, it's a little bit like killing a chicken with a knife , The method in this section is more concise .
Last mention , When combined with other operations such as normal data aggregation startswith() and endswith() The method is very good . such as , The following statement checks whether the specified file type exists in a folder :
if any(name.endswith(('.c', '.h')) for name in listdir(dirname)):
...
版权声明
本文为[Giant ship]所创,转载请带上原文链接,感谢
边栏推荐
猜你喜欢

价值超10亿美元的直播系统架构图是什么样子的?

sql 大小写转换,去掉前后空格

So what should investors do with the current market? Now a new investment outlet is coming!

Bifrost 位点管理 之 异构中间件实现难点(1)

做个别人家的网页

Gets the property value of a column in the list collection object

Win7 + vs2015 + cuda10.2 configuration tensorrt7.0

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

Must see! RDS database all in one

SQL case conversion, remove the space before and after
随机推荐
函数计算进阶-IP查询工具开发
Formal class D25
“wget: 无法解析主机地址”的解决方法
IP address SSL certificate
一幅图像能顶16x16字!——用于大规模图像缩放识别的变压器(对ICLR 2021年论文的简要回顾)
SRM系统是什么系统?SRM供应商管理系统功能
Function calculation advanced IP query tool development
Important components of Apache Hadoop
C++ exception implementation mechanism
接缝雕刻算法:一种看似不可能的图像大小调整方法
剑指offer之打印二叉搜索树中第k小的结点
Python中[:]与[::]的用法
Operation and design of rights management in ERP
Prometheus安装配置
pytorch训练GAN时的detach()
获取List集合对象中某一列属性值
公网IP地址和SSL证书可以提升SEO吗?
异常:Invalid or unexpected token
Baishan cloud technology is selected as the top 100 Internet enterprises in China in 2020
Common concepts and points for attention of CUDA