Python cookbook(字串與文本)在字串的開頭或結尾處進行文本匹配操作

來源:互聯網
上載者:User
這篇文章主要介紹了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》)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.