Python中用startswith()函數判斷字串開頭的教程

來源:互聯網
上載者:User
函數:startswith()

作用:判斷字串是否以指定字元或子字串開頭

一、函數說明
文法:string.startswith(str, beg=0,end=len(string))
或string[beg:end].startswith(str)

參數說明:
string: 被檢測的字串
str: 指定的字元或者子字串。(可以使用元組,會逐一匹配)
beg: 設定字串檢測的起始位置(可選)
end: 設定字串檢測的結束位置(可選)
如果存在參數 beg 和 end,則在指定範圍內檢查,否則在整個字串中檢查

傳回值
如果檢測到字串,則返回True,否則返回False。預設Null 字元為True

函數解析:如果字串string是以str開始,則返回True,否則返回False


二、執行個體

>>> s = 'hello good boy doiido'>>> print s.startswith('h')True>>> print s.startswith('hel')True>>> print s.startswith('h',4)False>>> print s.startswith('go',6,8)True#匹配Null 字元集>>> print s.startswith('')True#匹配元組>>> print s.startswith(('t','b','h'))True


常用環境:用於if判斷

>>> if s.startswith('hel'): print "you are right"else: print "you are wrang"you are right
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.