【python cookbook】【字符串与文本】2.在字符串的开头或结尾处做文本匹配
Python 字符串 文本 匹配 开头 Cookbook
2023-09-14 08:59:26 时间
问题:在字符串的开头或结尾处按照指定的文本模式做检查,例如检查文件的扩展名、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 编程 | 连载 05 - 字符串操作
- python字符串转化列表_Python列表到字符串的转换[通俗易懂]
- python fileinput_Python之fileinput模块学习「建议收藏」
- java和python哪个值得学-学java好还是Python好?
- python字符串格式化方法_format在python的意思
- python对csv文件的读写
- python物联网工具
- 【说站】python字符串对齐的三种方法
- 【说站】python partition如何分割字符串
- 【说站】python模块如何安装
- pycharm配置python解释器的问题_python解释器的提示符
- 代码也浪漫——Python烟花秀[通俗易懂]
- Python 生成随机数_python 随机字符串
- PyComplexHeatmap进阶教程:用python画热图的【行】/【列】注释信息
- 程序解码错误-由python的requests.post 请求结果乱码引起的思考
- python中常用的基础操作(1)——字符串
- Python基础语法-基本数据类型-字符串的格式化
- python-Python与MongoDB数据库-使用Python执行MongoDB查询(一)
- python-Python与PostgreSQL数据库-使用Python执行PostgreSQL查询(一)
- python统计文本字符串里面单词出现的频率详解编程语言
- 利用Neo4j和Python进行无缝图形数据库支持(neo4j python)
- python共享引用(多个变量引用)示例代码