Home > Backend Development > Python Tutorial > Python cookbook (String and Text) performs text matching operations at the beginning or end of a string

Python cookbook (String and Text) performs text matching operations at the beginning or end of a string

不言
Release: 2018-04-20 14:28:59
Original
1567 people have browsed it

这篇文章主要介绍了Python cookbook(字符串与文本)在字符串的开头或结尾处进行文本匹配操作,涉及Python使用str.startswith()和str.endswith()方法针对字符串开始或结尾处特定文本匹配操作相关实现技巧,需要的朋友可以参考下

本文实例讲述了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
>>>
Copy after login

若同时针对多个选项做检查,只需给函数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
Copy after login

最后,当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('文件存在')
文件存在
>>>
Copy after login

(代码摘自《Python Cookbook》)

相关推荐:

Python cookbook(数据结构与算法)将多个映射合并为单个映射

Python cookbook(字符串与文本)针对任意多的分隔符拆分字符串操作

The above is the detailed content of Python cookbook (String and Text) performs text matching operations at the beginning or end of a string. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template