歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python endswith() 函數 判斷字符串結尾

Python endswith() 函數 判斷字符串結尾

日期:2017/3/1 9:33:35   编辑:Linux編程

函數:endswith()

作用:判斷字符串是否以指定字符或子字符串結尾,常用於判斷文件類型
相關函數:判斷字符串開頭 startswith()

一、函數說明
語法:string.endswith(str, beg=[0,end=len(string)])
string[beg:end].endswith(str)

參數說明:
string: 被檢測的字符串
str: 指定的字符或者子字符串(可以使用元組,會逐一匹配)
beg: 設置字符串檢測的起始位置(可選,從左數起)
end: 設置字符串檢測的結束位置(可選,從左數起)
如果存在參數 beg 和 end,則在指定范圍內檢查,否則在整個字符串中檢查

返回值:
如果檢測到字符串,則返回True,否則返回False。

解析:如果字符串string是以str結束,則返回True,否則返回False

注:會認為空字符為真

二、實例

>>> s = 'hello good boy doiido'
>>> print s.endswith('o')
True
>>> print s.endswith('ido')
True
>>> print s.endswith('do',4)
True
>>> print s.endswith('do',4,15)
False

#匹配空字符集
>>> print s.endswith('')
True
#匹配元組
>>> print s.endswith(('t','b','o'))
True

常用環境:用於判斷文件類型(比如圖片,可執行文件)
>>> f = 'pic.jpg'
>>> if f.endswith(('.gif','.jpg','.png')):
print '%s is a pic' %f
else:
print '%s is not a pic' %f


pic.jpg is a pic

--------------------------------------分割線 --------------------------------------

CentOS上源碼安裝Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved