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

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

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

本文實(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í)針對多個(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文件與目錄操作技巧匯總

希望本文所述對大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評論