輕鬆python文本專題-字串開頭或者結尾匹配

來源:互聯網
上載者:User

標籤:python

情境:

字串開頭或者結尾匹配,一般是使用在匹配檔案類型或者url

一般使用startwith或者endwith

>>> a='http://blog.csdn.net/raylee2007'>>> a.startswith ('http')True

注意:這兩個方法裡面的參數可以是str,也可以是元組,但是不可以是列表和字典

>>> a='http://blog.csdn.net/raylee2007'>>> a.startswith (('http','ftp'))True

如果是列表或者字典,則報錯

>>> a='http://blog.csdn.net/raylee2007'>>> a.startswith (['http','ftp'])Traceback (most recent call last):  File "<pyshell#1>", line 1, in <module>    a.startswith (['http','ftp'])TypeError: startswith first arg must be str or a tuple of str, not list>>> 

其實,除了上面的方法, 也可以使用切片來實現,只不過代碼看上去沒那麼好看而已

>>> a='http://blog.csdn.net/raylee2007'>>> a[0:4]=='http'True>>> 


當然,我們也可以用Regex來做,但是理解上面就稍微難度有點。

>>> import re>>> url = 'http://www.python.org'>>> re.match('http:|https:|ftp:', url)<_sre.SRE_Match object; span=(0, 5), match='http:'>>>> help(re.match )Help on function match in module re:match(pattern, string, flags=0)    Try to apply the pattern at the start of the string, returning    a match object, or None if no match was found.>>> 


就說到這裡,謝謝大家

------------------------------------------------------------------

點擊跳轉零基礎學python-目錄


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

輕鬆python文本專題-字串開頭或者結尾匹配

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.