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判斷
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: --指定的字符或者子字符串(可以使用元組,會(huì)逐一匹配)
- beg: --設(shè)置字符串檢測的起始位置(可選,從左數(shù)起)
- end: --設(shè)置字符串檢測的結(jié)束位置(可選,從左數(shù)起)
- 如果存在參數(shù) beg 和 end,則在指定范圍內(nèi)檢查,否則在整個(gè)字符串中檢查
返回值:
如果檢測到字符串,則返回True,否則返回False。
解析:如果字符串string是以str結(jié)束,則返回True,否則返回False
注:會(huì)認(rèn)為空字符為真
''' 學(xué)習(xí)中遇到問題沒人解答?小編創(chuàng)建了一個(gè)Python學(xué)習(xí)交流群:531509025 尋找有志同道合的小伙伴,互幫互助,群里還有不錯(cuò)的視頻學(xué)習(xí)教程和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
到此這篇關(guān)于python中startswith()和endswith()的用法的文章就介紹到這了,更多相關(guān)python startswith()和endswith()用法內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。