Python: 字符串开头或结尾匹配str.startswith(),str.endswith()
问题
需要通过指定的文本模式去检查字符串的开头或者结尾,比如文件名后缀,URLScheme 等等。
解决方案
1.检查字符串开头或结尾的一个简单方法是使用str.startswith() 或者是str.endswith() 方法。比如:
eg1:
>>> filename = 'spam.txt'
>>> filename.endswith('.txt')
True
>>> filename.startswith('file:')
False
>>> url = 'http://www.python.org'
>>> url.startswith('http:')
True
如果想检查多种匹配可能,只需要将所有的匹配项放入到一个元组中去,然后传给startswith() 或者endswith() 方法:
eg2:
>>> import os
>>> filenames = os.listdir('.')
>>> filenames
[ 'Makefile', 'foo.c', 'bar.py', 'spam.c', 'spam.h' ]
>>> [name for name in filenames if name.endswith(('.c', '.h')) ]
['foo.c', 'spam.c', 'spam.h'
>>> any(name.endswith('.py') for name in filenames)
True
>>>
下面是另一个例子:
eg3:
from urllib.request import urlopen
def read_data(name):
if name.startswith(('http:', 'https:', 'ftp:')):
return urlopen(name).read()
else:
with open(name) as f:
return f.read()
奇怪的是,这个方法中必须要输入一个元组作为参数。如果你恰巧有一个list 或者set 类型的选择项,要确保传递参数前先调用tuple() 将其转换为元组类型。比如:
>>> choices = ['http:', 'ftp:']
>>> url = 'http://www.python.org'
>>> url.startswith(choices)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: startswith first arg must be str or a tuple of str, not list
>>> url.startswith(tuple(choices))
True
>>>
startswith() 和endswith() 方法提供了一个非常方便的方式去做字符串开头和结尾的检查。
2.类似的操作也可以使用切片来实现,但是代码看起来没有那么优雅。
eg:
>>> filename = 'spam.txt'
>>> filename[-4:] == '.txt'
True
>>> url = 'http://www.python.org'
>>> url[:5] == 'http:' or url[:6] == 'https:' or url[:4] == 'ftp:'
True
>>>
3.你可以能还想使用正则表达式去实现,
eg:
>>> import re
>>> url = 'http://www.python.org'
>>> re.match('http:jhttps:jftp:', url)
<_sre.SRE_Match object at 0x101253098>
>>>
这种方式也行得通,但是对于简单的匹配实在是有点小材大用了,本节中的方法更加简单并且运行会更快些。
最后提一下,当和其他操作比如普通数据聚合相结合的时候startswith() 和endswith() 方法是很不错的。比如,下面这个语句检查某个文件夹中是否存在指定的文件类型:
if any(name.endswith(('.c', '.h')) for name in listdir(dirname)):
- python 4-2 如何判断字符串a是否以字符串b开头或结尾str.startswith/os.stat(filename)/stat.S_IRWXU
- 对python 匹配字符串开头和结尾的方法详解
- python 字符串开头或结尾匹配
- 轻松python文本专题-字符串开头或者结尾匹配
- Python-字符串开头或结尾匹配
- 轻松python文本专题-字符串开头或者结尾匹配
- Python startswith() 函数 判断字符串开头
- Python3基础 str endswith 检查字符串是否以指定字符串结束
- 轻松python文本专题-字符串开头或者结尾匹配
- python文本 字符串开头或者结尾匹配
- python 匹配字符串开头和结尾
- js Strong.prototype.endsWith 查看某个字符串是不是以另外一个字符串结尾
- python 正则表达式:匹配字符串开头并打印
- python_如何判断字符串a以某个字符串开头或结尾?
- 在Python中操作字符串之startswith()方法的使用
- python使用正则表达式匹配字符串开头并打印示例
- 老生常谈Python startswith()函数与endswith函数
- Python中处理字符串之endswith()方法的使用简介
- Python: 去掉字符串开头、结尾或者中间不想要的字符
- python str.replace / str.endswith 以及 python语句(返回目录中所有JPG图像的文件名列表)