Python cookbook中如何在字符串的开头或结尾处进行文本匹配操作

这篇文章主要为大家展示了“Python cookbook中如何在字符串的开头或结尾处进行文本匹配操作”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“Python cookbook中如何在字符串的开头或结尾处进行文本匹配操作”这篇文章吧。

问题:在字符串的开头或结尾处按照指定的文本模式做检查,例如检查文件的扩展名、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中如何在字符串的开头或结尾处进行文本匹配操作”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注行业资讯频道!