本文摘自php中文网,作者不言,侵删。
这篇文章主要介绍了Python cookbook(字符串与文本)在字符串的开头或结尾处进行文本匹配操作,涉及Python使用str.startswith()和str.endswith()方法针对字符串开始或结尾处特定文本匹配操作相关实现技巧,需要的朋友可以参考下本文实例讲述了Python在字符串的开头或结尾处进行文本匹配操作。分享给大家供大家参考,具体如下:
问题:在字符串的开头或结尾处按照指定的文本模式做检查,例如检查文件的扩展名、URL协议类型等;
解决方法:使用str.startswith()
和str.endswith()
方法
1 2 3 4 5 6 7 8 9 10 11 | >>> 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()
提供包含多个可能选项的元组即可:
1 2 3 4 5 6 7 8 9 10 11 12 | >>> 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()
方法和其他操作(比如常见的数据整理操作)结合起来时效果也很好。例如,下面的语句检查目录中有无出现特定的文件:
1 2 3 4 5 6 7 8 | >>> 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 cookbook(数据结构与算法)将多个映射合并为单个映射
Python cookbook(字符串与文本)针对任意多的分隔符拆分字符串操作
以上就是Python cookbook(字符串与文本)在字符串的开头或结尾处进行文本匹配操作的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
序列化和反序列化的详细介绍
Python有64位的吗
数据分析师为什么要学Python
Python怎么创建列表
Python学什么方向
Python的tornado之websocket的概念以及应用介绍
Python怎么避免随机元素重复
visual studio 创建 Python flaskweb 项目运行时报“no module named flask”错
Python和pycharm什么关系
Python如何生成词云的方法
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python cookbook(字符串与文本)在字符串的开头或结尾处进行文本匹配操作