Python cookbook(字符串與文本)在字符串的開頭或結(jié)尾處進行文本匹配操作
本文實例講述了Python在字符串的開頭或結(jié)尾處進行文本匹配操作。分享給大家供大家參考,具體如下:
問題:在字符串的開頭或結(jié)尾處按照指定的文本模式做檢查,例如檢查文件的擴展名、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ù)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()
方法和其他操作(比如常見的數(shù)據(jù)整理操作)結(jié)合起來時效果也很好。例如,下面的語句檢查目錄中有無出現(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》)
更多關于Python相關內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
相關文章
python使用xauth方式登錄飯否網(wǎng)然后發(fā)消息
這篇文章主要介紹了python使用xauth方式登錄飯否網(wǎng)然后發(fā)消息示例,需要的朋友可以參考下2014-04-04Python?第三方庫?Pandas?數(shù)據(jù)分析教程
這篇文章主要介紹了Python?第三方庫?Pandas?數(shù)據(jù)分析教程的相關資料,需要的朋友可以參考下2022-09-09基于python實現(xiàn)的百度新歌榜、熱歌榜下載器(附代碼)
這篇文章主要介紹了基于python實現(xiàn)的百度新歌榜、熱歌榜下載器(附代碼),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-08-08