Python startswith()和endswith() 方法原理解析
startswith()方法
Python startswith() 方法用于檢查字符串是否是以指定子字符串開(kāi)頭
如果是則返回 True,否則返回 False。如果參數(shù) beg 和 end 指定值,則在指定范圍內(nèi)檢查。
str.startswith(str, beg=0,end=len(string));
參數(shù)
str --檢測(cè)的字符串。 strbeg --可選參數(shù)用于設(shè)置字符串檢測(cè)的起始位置。 strend --可選參數(shù)用于設(shè)置字符串檢測(cè)的結(jié)束位置。返回值
如果檢測(cè)到字符串則返回True,否則返回False。
常用環(huán)境:用于IF判斷
#!/usr/local/bin/python# coding=utf-8listsql = ’select * from ifrs.indiv_info’def isSelect(sql): chsql = sql.upper().strip() if not chsql.startswith('SELECT '): return False return Trueprint isSelect(listsql)[root@bigdata-poc-shtz-3 zw]# python h.pyTrue
endswith()方法
作用:判斷字符串是否以指定字符或子字符串結(jié)尾,常用于判斷文件類(lèi)型
一、函數(shù)說(shuō)明
語(yǔ)法:string.endswith(str, beg=[0,end=len(string)])
string[beg:end].endswith(str)
參數(shù)說(shuō)明:
string: --被檢測(cè)的字符串 str: --指定的字符或者子字符串(可以使用元組,會(huì)逐一匹配) beg: --設(shè)置字符串檢測(cè)的起始位置(可選,從左數(shù)起) end: --設(shè)置字符串檢測(cè)的結(jié)束位置(可選,從左數(shù)起)如果存在參數(shù) beg 和 end,則在指定范圍內(nèi)檢查,否則在整個(gè)字符串中檢查
返回值:
如果檢測(cè)到字符串,則返回True,否則返回False。
解析:如果字符串string是以str結(jié)束,則返回True,否則返回False
注:會(huì)認(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)境:用于判斷文件類(lèi)型(比如圖片,可執(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
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. React+umi+typeScript創(chuàng)建項(xiàng)目的過(guò)程2. ASP調(diào)用WebService轉(zhuǎn)化成JSON數(shù)據(jù),附j(luò)son.min.asp3. php測(cè)試程序運(yùn)行速度和頁(yè)面執(zhí)行速度的代碼4. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究5. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執(zhí)行過(guò)程解析6. 無(wú)線標(biāo)記語(yǔ)言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁(yè)7. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報(bào)錯(cuò)問(wèn)題分析8. ASP中常用的22個(gè)FSO文件操作函數(shù)整理9. SharePoint Server 2019新特性介紹10. 三個(gè)不常見(jiàn)的 HTML5 實(shí)用新特性簡(jiǎn)介
