1. 程式人生 > >Python: 字符串開頭或結尾匹配str.startswith(),str.endswith()

Python: 字符串開頭或結尾匹配str.startswith(),str.endswith()

recent tdi 如果 簡單的 後綴 body round 方案 實現

問題

需要通過指定的文本模式去檢查字符串的開頭或者結尾,比如文件名後綴,URLScheme 等等。


解決方案


1.檢查字符串開頭或結尾的一個簡單方法是使用str.startswith() 或者是str.endswith() 方法。比如:

eg1:
>>> filename = ‘spam.txt‘
>>> filename.endswith(‘.txt‘)
True
>>> filename.startswith(‘file:‘)
False
>>> url = ‘http://www.python.org‘
>>> url.startswith(‘http:‘)


True

如果想檢查多種匹配可能,只需要將所有的匹配項放入到一個元組中去,然後傳給startswith() 或者endswith() 方法:

eg2:
>>> 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
>>>


下面是另一個例子:

eg3:
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
>>>

startswith() 和endswith() 方法提供了一個非常方便的方式去做字符串開頭和結尾的檢查。

2.類似的操作也可以使用切片來實現,但是代碼看起來沒有那麽優雅。


eg:
>>> filename = ‘spam.txt‘
>>> filename[-4:] == ‘.txt‘
True
>>> url = ‘http://www.python.org‘
>>> url[:5] == ‘http:‘ or url[:6] == ‘https:‘ or url[:4] == ‘ftp:‘
True
>>>

3.你可以能還想使用正則表達式去實現,

eg:
>>> import re
>>> url = ‘http://www.python.org‘
>>> re.match(‘http:jhttps:jftp:‘, url)
<_sre.SRE_Match object at 0x101253098>
>>>
這種方式也行得通,但是對於簡單的匹配實在是有點小材大用了,本節中的方法更加簡單並且運行會更快些。


最後提一下,當和其他操作比如普通數據聚合相結合的時候startswith() 和endswith() 方法是很不錯的。比如,下面這個語句檢查某個文件夾中是否存在指定的文件類型:
if any(name.endswith((‘.c‘, ‘.h‘)) for name in listdir(dirname)):

Python: 字符串開頭或結尾匹配str.startswith(),str.endswith()