当前位置:网站首页>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]所创,转载请带上原文链接,感谢
边栏推荐
猜你喜欢
Can public IP address and SSL certificate improve SEO?
C++ exception implementation mechanism
Coding style: SSM environment in MVC mode, code hierarchical management
做个别人家的网页
Explanation of Z-index attribute
Application of V7 version of lvgl Library
Function calculation advanced IP query tool development
对于程序员,那些既陌生又熟悉的计算机硬件
Centos7 operating system security hardening series (2)
November 09, 2020: talk about the similarities and differences between the bulon filter and the cuckoo filter?
随机推荐
Interviewer: what are cache penetration, cache avalanche and cache breakdown?
js解决浏览器打印自动分页的问题
mongodb内核源码实现、性能调优、最佳运维实践系列-command命令处理模块源码实现一
JT Jingtao project
将Map中对应的key和value赋值到对象中
sql 大小写转换,去掉前后空格
Simple use of JMeter
Algorithm template arrangement (1)
What is the architecture of a live broadcast system worth more than $1 billion?
Brief analysis of LinkedList source code
利用尾巴作为时间序列进行处理来识别鲸鱼
Validation failed for one or more entities. See ‘EntityValidationErrors’解决方法
CUDA_ Memory model
leetcode之最后一个单词的长度
利用尾巴作为时间序列进行处理来识别鲸鱼
CUDA_存储器模型
JMeter的简单使用
公网IP地址和SSL证书可以提升SEO吗?
CUDA_获取指定设备
算法模板整理(一)