Python中的startswith和endswith函數使用執行個體

來源:互聯網
上載者:User
在Python中有兩個函數分別是startswith()函數與endswith()函數,功能都十分相似,startswith()函數判斷文本是否以某個字元開始,endswith()函數判斷文本是否以某個字元結束。

startswith()函數

此函數判斷一個文本是否以某個或幾個字元開始,結果以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('') # True

endswith()函數

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

代碼如下:


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 ') # False

判斷檔案是否為exe執行檔案

我們可以利用endswith()函數判斷檔案名稱的是不是以.exe尾碼結尾判斷是否為可執行檔

代碼如下:


# coding=utf8

fileName1='qttc.exe'
if(fileName1.endswith('.exe')):
print '這是一個exe執行檔案'
else:
print '這不是一個exe執行檔案'

# 執行結果:這是一個exe執行檔案

判斷檔案名稱尾碼是否為圖片

代碼如下:


# coding=utf8

fileName1='pic.jpg'
if fileName1.endswith('.gif') or fileName1.endswith('.jpg') or fileName1.endswith('.png'):
print '這是一張圖片'
else:
print '這不是一張圖片'

# 執行結果:這是一張圖片

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.