在字串的開頭或結尾處做文字匹配
阿新 • • 發佈:2020-07-20
問題:
我們需要在字串的開頭或結尾處按照指定的文字模式做檢查,例如檢查檔案的副檔名、URL協議型別等。
解決方案:
有一種簡單的方法可用來檢查字串的開頭或結尾,只要使用str.startswith()和str.endswith()方法就可以了
1 filename = 'spam.txt' 2 result = filename.endswith('.txt') 3 print(result) 4 5 result1 = filename.startswith('file:') 6 print(result1) 7 8 url = "http://www.python.org" 9 result2 = url.startswith('http:') 10 print(result2)
執行結果:
True
False
True
如果需要同時針對多個選項做檢查,只需給startswith()和endswith()提供包含可能選項的元組即可:
import os filenames = os.listdir('.') print(filenames) result = [name for name in filenames if name.endswith(('.py','.txt'))] print(result) result1 = any(name.endswith('.py') for name in filenames) print(result1)
結果:
['2_2_1.py', '11.txt', '2_1.py', '2_2.py'] ['2_2_1.py', '11.txt', '2_1.py', '2_2.py'] True