溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Python startswith()和endswith()方法的用法

發(fā)布時間:2020-07-29 14:24:40 來源:億速云 閱讀:156 作者:小豬 欄目:開發(fā)技術

這篇文章主要講解了Python startswith()和endswith()方法的用法,內(nèi)容清晰明了,對此有興趣的小伙伴可以學習一下,相信大家閱讀完之后會有幫助。

startswith()方法

Python startswith() 方法用于檢查字符串是否是以指定子字符串開頭

如果是則返回 True,否則返回 False。如果參數(shù) beg 和 end 指定值,則在指定范圍內(nèi)檢查。

str.startswith(str, beg=0,end=len(string));

參數(shù)

  • str --檢測的字符串。
  • strbeg --可選參數(shù)用于設置字符串檢測的起始位置。
  • strend --可選參數(shù)用于設置字符串檢測的結束位置。

返回值

如果檢測到字符串則返回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()方法

作用:判斷字符串是否以指定字符或子字符串結尾,常用于判斷文件類型

一、函數(shù)說明

語法:string.endswith(str, beg=[0,end=len(string)])

string[beg:end].endswith(str)

參數(shù)說明:

  • string: --被檢測的字符串
  • str: --指定的字符或者子字符串(可以使用元組,會逐一匹配)
  • beg: --設置字符串檢測的起始位置(可選,從左數(shù)起)
  • end: --設置字符串檢測的結束位置(可選,從左數(shù)起)

如果存在參數(shù) beg 和 end,則在指定范圍內(nèi)檢查,否則在整個字符串中檢查

返回值:

如果檢測到字符串,則返回True,否則返回False。

解析:如果字符串string是以str結束,則返回True,否則返回False

注:會認為空字符為真

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)容,是不是對Python startswith()和endswith()方法的用法有進一步的了解,如果還想學習更多內(nèi)容,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI