Python中的startswith和endswith函數使用實例

在Python中有兩個函數分別是startswith()函數與endswith()函數,功能都十分類似,startswith()函數判斷文本是否以某個字符開始,endswith()函數判斷文本是否以某個字符結束。函數

startswith()函數blog

此函數判斷一個文本是否以某個或幾個字符開始,結果以True或者False返回。圖片

text='welcome to qttc blog'
print text.startswith('w')      # True
print text.startswith('wel')    # True
print text.startswith('c')      # False
print text.startswith('')       # Trueqt

endswith()函數it

此函數判斷一個文本是否以某個或幾個字符結束,結果以True或者False返回。coding

text='welcome to qttc blog'
print text.endswith('g')        # True
print text.endswith('go')       # False
print text.endswith('og')       # True
print text.endswith('')         # True
print text.endswith('g ')       # Falsefile

 

判斷文件是否爲exe執行文件di

咱們能夠利用endswith()函數判斷文件名的是否是以.exe後綴結尾判斷是否爲可執行文件文件

# coding=utf8
 
fileName1='qttc.exe'
if(fileName1.endswith('.exe')):
    print '這是一個exe執行文件'   
else:
    print '這不是一個exe執行文件'
 
# 執行結果:這是一個exe執行文件co

判斷文件名後綴是否爲圖片

# coding=utf8   fileName1='pic.jpg' if fileName1.endswith('.gif') or fileName1.endswith('.jpg') or fileName1.endswith('.png'):     print '這是一張圖片' else:     print '這不是一張圖片'       # 執行結果:這是一張圖片

相關文章
相關標籤/搜索