這篇文章主要介紹了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>>>
若同時針對多個選項做檢查,只需給函數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()
方法和其他動作(比如常見的資料整理操作)結合起來時效果也很好。例如,下面的語句檢查目錄中有無出現特定的檔案:
>>> 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》)