本文實(shí)例講述了Python在字符串的開頭或結(jié)尾處進(jìn)行文本匹配操作。分享給大家供大家參考,具體如下:
問題:在字符串的開頭或結(jié)尾處按照指定的文本模式做檢查,例如檢查文件的擴(kuò)展名、URL協(xié)議類型等;
解決方法:使用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>>> 若同時(shí)針對(duì)多個(gè)選項(xiàng)做檢查,只需給函數(shù)startswith()和str.endswith()提供包含多個(gè)可能選項(xiàng)的元組即可:
>>> 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最后,當(dāng)startswith()和str.endswith()方法和其他操作(比如常見的數(shù)據(jù)整理操作)結(jié)合起來時(shí)效果也很好。例如,下面的語句檢查目錄中有無出現(xiàn)特定的文件:
>>> 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》)
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選