問題
通過指定的文本模式去檢查字符串的開頭或者結(jié)尾,比如文件名后綴,URL Scheme等等。
解決方案
檢查字符串開頭或結(jié)尾的一個簡單方法是使用 str.startswith() 或者是 str.endswith() 方法。比如:
file_name = 'test.txt'
print(file_name.endswith('.txt'))
True
url = 'www.google.com'
print(url.startswith('www.'))
True
如果想檢查多種匹配可能,需要將所有的匹配項(xiàng)放入到一個元組中, 傳給 startswith() 或者 endswith() 方法:
file_up = os.listdir(os.chdir('../'))
f_name = [f for f in file_up if f.endswith(('__', '.py'))]
print(file_up)
print(f_name)
['.DS_Store', 'decorator', 'module', 'cookbook', '__pycache__', 'test.py', 'class']
['__pycache__', 'test.py']
startswith() 和 endswith() 方法提供了一個非常方便的方式去做字符串開頭和結(jié)尾的檢查。 類似的操作也可以使用切片來實(shí)現(xiàn),但是代碼看起來沒有那么優(yōu)雅。比如:
print(file_name[4:] == '.txt')
print(url[:4] == 'www.')
True
True