欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2018年04月20日 14:17:31   作者:壟上行  
這篇文章主要介紹了Python cookbook(字符串與文本)在字符串的開頭或結(jié)尾處進行文本匹配操作,涉及Python使用str.startswith()和str.endswith()方法針對字符串開始或結(jié)尾處特定文本匹配操作相關實現(xiàn)技巧,需要的朋友可以參考下

本文實例講述了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程序設計有所幫助。

相關文章

最新評論