Python startswith()和endswith() 方法原理解析
startswith()方法
Python startswith() 方法用于檢查字符串是否是以指定子字符串開頭
如果是則返回 True,否則返回 False。如果參數(shù) beg 和 end 指定值,則在指定范圍內(nèi)檢查。
str.startswith(str, beg=0,end=len(string));
參數(shù)
- str --檢測的字符串。
- strbeg --可選參數(shù)用于設(shè)置字符串檢測的起始位置。
- strend --可選參數(shù)用于設(shè)置字符串檢測的結(jié)束位置。
返回值
如果檢測到字符串則返回True,否則返回False。
常用環(huán)境:用于IF判斷
#!/usr/local/bin/python # coding=utf-8 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()方法
作用:判斷字符串是否以指定字符或子字符串結(jié)尾,常用于判斷文件類型
一、函數(shù)說明
語法:string.endswith(str, beg=[0,end=len(string)])
string[beg:end].endswith(str)
參數(shù)說明:
- string: --被檢測的字符串
- str: --指定的字符或者子字符串(可以使用元組,會逐一匹配)
- beg: --設(shè)置字符串檢測的起始位置(可選,從左數(shù)起)
- end: --設(shè)置字符串檢測的結(jié)束位置(可選,從左數(shù)起)
如果存在參數(shù) beg 和 end,則在指定范圍內(nèi)檢查,否則在整個字符串中檢查
返回值:
如果檢測到字符串,則返回True,否則返回False。
解析:如果字符串string是以str結(jié)束,則返回True,否則返回False
注:會認(rèn)為空字符為真
python
>>> 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
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python如何實現(xiàn)后端自定義認(rèn)證并實現(xiàn)多條件登陸
這篇文章主要介紹了Python如何實現(xiàn)后端自定義認(rèn)證并實現(xiàn)多條件登陸,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-06-06在python下實現(xiàn)word2vec詞向量訓(xùn)練與加載實例
這篇文章主要介紹了在python下實現(xiàn)word2vec詞向量訓(xùn)練與加載實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06Python簡繁體轉(zhuǎn)換的簡單實現(xiàn)步驟
工作中需要將繁體中文轉(zhuǎn)換成簡體中文上網(wǎng)找了些資料,下面這篇文章主要給大家介紹了關(guān)于Python實現(xiàn)簡繁體轉(zhuǎn)換的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-06-06