Python cookbook(字符串与文本)在字符串的开头或结尾处进行文本匹配操作

yipeiwu_com5年前Python基础

本文实例讲述了Python在字符串的开头或结尾处进行文本匹配操作。分享给大家供大家参考,具体如下:

问题:在字符串的开头或结尾处按照指定的文本模式做检查,例如检查文件的扩展名、URL协议类型等;

解决方法:使用str.startswith()str.endswith()方法

>>> filename='spam.txt'
>>> filename.endswith('.txt')
True
>>> filename.startswith('file:')
False
>>> url='http://www.python.org'
>>> url.startswith('htto:')
False
>>> url.startswith('http:')
True
>>> 

若同时针对多个选项做检查,只需给函数startswith()str.endswith()提供包含多个可能选项的元组即可:

>>> import os
>>> os.getcwd()
'D:\\4autotests\\02script\\pythonbase'
>>> os.listdir()
['foo.py', 'hello.txt', 'Makefile', 'spam.c', 'spam.h', 'test1.py']
>>> filename=os.listdir()
>>> filename
['foo.py', 'hello.txt', 'Makefile', 'spam.c', 'spam.h', 'test1.py']
>>> [name for name in filename if name.endswith(('.c','.h'))]
['spam.c', 'spam.h']
>>> any(name.endswith('.py') for name in filename)
True

最后,当startswith()str.endswith()方法和其他操作(比如常见的数据整理操作)结合起来时效果也很好。例如,下面的语句检查目录中有无出现特定的文件:

>>> os.getcwd()
'D:\\4autotests\\02script\\pythonbase'
>>> os.listdir()
['foo.py', 'hello.txt', 'Makefile', 'spam.c', 'spam.h', 'test1.py']
>>> if any(name.endswith(('.txt','.py')) for name in os.listdir(os.getcwd())):
  print('文件存在')
文件存在
>>> 

(代码摘自《Python Cookbook》)

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

python使用Tkinter显示网络图片的方法

本文实例讲述了python使用Tkinter显示网络图片的方法。分享给大家供大家参考。具体实现方法如下: ''' tk_image_view_url_io.py display an...

python中列表元素连接方法join用法实例

本文实例讲述了python中列表元素连接方法join用法。分享给大家供大家参考。具体分析如下: 创建列表: >>> music = ["Abba","Rollin...

python多行字符串拼接使用小括号的方法

多行字符串拼接使用小括号 s = ('select *' 'from atable' 'where id=888') print s, type(s) #输出 select...

Python解析树及树的遍历

Python解析树及树的遍历

解析树 完成树的实现之后,现在我们来看一个例子,告诉你怎么样利用树去解决一些实际问题。在这个章节,我们来研究解析树。解析树常常用于真实世界的结构表示,例如句子或数学表达式。 图 1:一...

win10安装tensorflow-gpu1.8.0详细完整步骤

win10安装tensorflow-gpu1.8.0详细完整步骤

在整个安装的过程中也遇到了很多的坑,故此做个记录,争取下次不再犯! 我的整个基本配置如下: 电脑环境如下:win10(64位)+CPU:E5-2603 +GPU:GTX 1070 需要安...