本篇文章給大家分享的是有關怎么在python中匹配字符串開頭和結尾,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
1、你需要通過指定的文本模式去檢查字符串的開頭或者結尾,比如文件名后綴,URL Scheme 等等。檢 查 字 符 串 開 頭 或 結 尾 的 一 個 簡 單 方 法 是 使 用str.startswith() 或 者 是str.endswith()方法。比如:
>>> filename = 'spam.txt' >>> filename.endswith('.txt') True >>> filename.startswith('file:') False >>> url = 'http://www.python.org' >>> url.startswith('http:') True >>>
2、如果你想檢查多種匹配可能,只需要將所有的匹配項放入到一個元組中去,然后傳給 startswith()或者 endswith() 方法:
>>> import os >>> filenames = os.listdir('.') >>> filenames [ 'Makefile', 'foo.c', 'bar.py', 'spam.c', 'spam.h' ] >>> [name for name in filenames if name.endswith(('.c', '.h')) ] ['foo.c', 'spam.c', 'spam.h' >>> any(name.endswith('.py') for name in filenames) True >>> #示例2 from urllib.request import urlopen def read_data(name): if name.startswith(('http:', 'https:', 'ftp:')): return urlopen(name).read() else: with open(name) as f: return f.read()
奇怪的是,這個方法中必須要輸入一個元組作為參數。如果你恰巧有一個list 或者 set類型的選擇項,要確保傳遞參數前先調用 tuple()將其轉換為元組類型。比如:
>>> choices = ['http:', 'ftp:'] >>> url = 'http://www.python.org' >>> url.startswith(choices) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: startswith first arg must be str or a tuple of str, not list >>> url.startswith(tuple(choices)) True >>>
3、startswith() 和 endswith() 方法提供了一個非常方便的方式去做字符串開頭和結尾的檢查。類似的操作也可以使用切片來實現,但是代碼看起來沒有那么優雅。比如:
>>> filename = 'spam.txt' >>> filename[-4:] == '.txt' True >>> url = 'http://www.python.org' >>> url[:5] == 'http:' or url[:6] == 'https:' or url[:4] == 'ftp:' True >>>
4、你可以能還想使用正則表達式去實現,比如:
>>> import re >>> url = 'http://www.python.org' >>> re.match('http:jhttps:jftp:', url) <_sre.SRE_Match object at 0x101253098> >>>
5、當和其他操作比如普通數據聚合相結合的時候 startswith()和endswith() 方法是很不錯的。比如,下面這個語句檢查某個文件夾中是否存在指定的文件類型:
if any(name.endswith(('.c', '.h')) for name in listdir(dirname)): ...
1、簡單易用,與C/C++、Java、C# 等傳統語言相比,Python對代碼格式的要求沒有那么嚴格;2、Python屬于開源的,所有人都可以看到源代碼,并且可以被移植在許多平臺上使用;3、Python面向對象,能夠支持面向過程編程,也支持面向對象編程;4、Python是一種解釋性語言,Python寫的程序不需要編譯成二進制代碼,可以直接從源代碼運行程序;5、Python功能強大,擁有的模塊眾多,基本能夠實現所有的常見功能。
以上就是怎么在python中匹配字符串開頭和結尾,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。