Python-字符串开头或结尾匹配

startswith()endswith() 方法提供了一个非常方便的方式去做字符串开头和结尾的检查。

1、查看指定目录下的所有文件名

>>> import os
>>> filenames = os.listdir('I:\PythonTest')
>>> filenames
['111.csv', '111.xlsx', '111.xml', '123.txt', '123.xlsx', '123123.xml', '123123.xml.bak', '1234.txt', '222.xml', 'book.xml', 'book.xml.bak', 'excelWrite.csv', 'excelWrite.xlsx', 'Koala.jpg', 'movie.xml', 'movie.xml.bak', 'movies.xml', 'receive.txt', 'user.xml', 'user.xml.bak', '新建文件夹']

2、列出.txt文件名

>>> for i in filenames:
if i.endswith('.txt'):
print(i) 123.txt
1234.txt
receive.txt

另外一种写法:

>>> i for i in filenames if i.endswith('.txt')
SyntaxError: invalid syntax
>>> [i for i in filenames if i.endswith('.txt')] #结果返回一个list[]
['123.txt', '1234.txt', 'receive.txt']
>>> a = [i for i in filenames if i.endswith('.txt')]
>>> print(a)
['123.txt', '1234.txt', 'receive.txt']

3、同时列出.txt和.xml文件

如果你想检查多种匹配可能,只需要将所有的匹配项放入到一个元组(‘a’,’b’,’c’)中去, 然后传给startswith() 或者 endswith() 方法

>>> for i in filenames:
if i.endswith(('.txt','.xml')):
print(i) 111.xml
123.txt
123123.xml
1234.txt
222.xml
book.xml
movie.xml
movies.xml
receive.txt
user.xml
>>> [i for i in filenames if i.endswith(('.txt','.xml'))]
['111.xml', '123.txt', '123123.xml', '1234.txt', '222.xml', 'book.xml', 'movie.xml', 'movies.xml', 'receive.txt', 'user.xml']

4、列出开头为book和1的文件名

>>> [i for i in filenames if i.startswith(('book',''))]
['111.csv', '111.xlsx', '111.xml', '123.txt', '123.xlsx', '123123.xml', '123123.xml.bak', '1234.txt', 'book.xml', 'book.xml.bak']

5、查看是否存在xml的文件

检查某个文件夹中是否存在指定的文件类型:

if any(name.endswith(('.c', '.h')) for name in listdir(dirname)):
>>> any(name.endswith('.xml') for name in filenames)
True

参考资料:http://python3-cookbook.readthedocs.org/zh_CN/latest/c02/p02_match_text_at_start_end.html

上一篇:oh my zsh命令


下一篇:POJ-1068 Parencodings---模拟括号的配对