startswith()方法
Python startswith() 方法用于檢查字串是否是以指定子字串開頭
如果是則回傳 True,否則回傳 False,如果引數 beg 和 end 指定值,則在指定范圍內檢查,
str.startswith(str, beg=0,end=len(string));
引數
- str --檢測的字串,
- strbeg --可選引數用于設定字串檢測的起始位置,
- strend --可選引數用于設定字串檢測的結束位置,
回傳值
如果檢測到字串則回傳True,否則回傳False,
常用環境:用于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
注:會認為空字符為真
'''
學習中遇到問題沒人解答?小編創建了一個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
常用環境:用于判斷檔案型別(比如圖片,可執行檔案)
>>> 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/309388.html
標籤:Python
