python中startswith()和endswith()的用法詳解
startswith()方法
Python startswith() 方法用于檢查字符串是否是以指定子字符串開頭
如果是則返回 True,否則返回 False。如果參數 beg 和 end 指定值,則在指定范圍內檢查。
str.startswith(str, beg=0,end=len(string));
參數
- str --檢測的字符串。
- strbeg --可選參數用于設置字符串檢測的起始位置。
- strend --可選參數用于設置字符串檢測的結束位置。
返回值
如果檢測到字符串則返回True,否則返回False。
常用環(huán)境:用于IF判斷
listsql = 'select * from ifrs.indiv_info' def isSelect(sql): chsql = sql.upper().strip() if not chsql.startswith("SELECT "): return False return True print isSelect(listsql) [root@bigdata-poc-shtz-3 zw]# python h.py True
endswith()方法
作用:判斷字符串是否以指定字符或子字符串結尾,常用于判斷文件類型
函數說明
語法:
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
注:會認為空字符為真
''' 學習中遇到問題沒人解答?小編創(chuàng)建了一個Python學習交流群:531509025 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' >>> endsql = 'select * from ifrs.indiv_info' >>> endsql.endswith('info') True >>> endsql.endswith('info',3) True >>> >>> endsql.endswith('info',3,10) False >>> endsql.endswith('info',25,29) True >>> endsql.endswith('') True
常用環(huán)境:用于判斷文件類型(比如圖片,可執(zhí)行文件)
>>> f = 'a.txt' >>> if f.endswith(('.txt')): ... print '%s is a txt' %f ... else: ... print '%s is not a txt' %f ... a.txt is a txt
到此這篇關于python中startswith()和endswith()的用法的文章就介紹到這了,更多相關python startswith()和endswith()用法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python中torch.load()加載模型以及其map_location參數詳解
torch.load()作用用來加載torch.save()保存的模型文件,下面這篇文章主要給大家介紹了關于Python中torch.load()加載模型以及其map_location參數的相關資料,需要的朋友可以參考下2022-09-09利用Python自帶PIL庫擴展圖片大小給圖片加文字描述的方法示例
最近的一個工程項目是講文字添加到圖像上,所以下面這篇文章主要給大家介紹了關于利用Python自帶PIL庫擴展圖片大小給圖片加文字描述的相關資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考借鑒,下面來一起看看吧。2017-08-08