对python 匹配字符串开头和结尾的方法详解

yipeiwu_com5年前Python基础

1、你需要通过指定的文本模式去检查字符串的开头或者结尾,比如文件名后缀,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
>>> 

2、如果你想检查多种匹配可能,只需要将所有的匹配项放入到一个元组中去,然后传给 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
>>>
 
#示例2
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
>>>

3、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
>>>

4、你可以能还想使用正则表达式去实现,比如:

>>> import re
>>> url = 'http://www.python.org'
>>> re.match('http:jhttps:jftp:', url)
<_sre.SRE_Match object at 0x101253098>
>>>

5、当和其他操作比如普通数据聚合相结合的时候 startswith()和endswith() 方法是很不错的。比如,下面这个语句检查某个文件夹中是否存在指定的文件类型:

if any(name.endswith(('.c', '.h')) for name in listdir(dirname)):
...

以上这篇对python 匹配字符串开头和结尾的方法详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python手机号码归属地查询代码

Python手机号码归属地查询代码

简单的一个例子,是以前用Dephi写的,前不久刚实现了一个在Python中使用Delphi控件来编写界面程序,于是趁热写一个类似的的查询方案。 本实例是通过www.ip138.com这...

Python matplotlib学习笔记之坐标轴范围

Python matplotlib学习笔记之坐标轴范围

Python学习笔记--坐标轴范围 参靠视频:《Python数据可视化分析 matplotlib教程》链接:https://www.bilibili.com/video/av698941...

python的多重继承的理解

python的多重继承的理解

python的多重继承的理解 Python和C++一样,支持多继承。概念虽然容易,但是困难的工作是如果子类调用一个自身没有定义的属性,它是按照何种顺序去到父类寻找呢,尤其是众多父类中有多...

Python编程scoketServer实现多线程同步实例代码

本文研究的主要是Python编程scoketServer实现多线程同步的相关内容,具体介绍如下。 开发过程中,为了实现不同的客户端同一时刻只能有一个使用共同数据。 虽说用Python编写...

黑科技 Python脚本帮你找出微信上删除你好友的人

黑科技 Python脚本帮你找出微信上删除你好友的人

相信大家在微信上一定被上面的这段话刷过屏,群发消息应该算是微信上流传最广的找到删除好友的方法了。但群发消息不仅仅会把通讯录里面所有的好友骚扰一遍,而且你还得挨个删除好几百个聊天记录,回复...