python文本 字符串開(kāi)頭或者結(jié)尾匹配

2022-07-04 15:12 更新

python 文本 字符串開(kāi)頭或者結(jié)尾匹配

場(chǎng)景:

字符串開(kāi)頭或者結(jié)尾匹配,一般是使用在匹配文件類(lèi)型或者 url

一般使用 startwith 或者 endwith

  >>> a='http://www.o2fo.com/vip'  
  >>> a.startswith ('http')  
  True  

注意:這兩個(gè)方法里面的參數(shù)可以是 str,也可以是元組,但是不可以是列表和字典

  >>> a='http://www.o2fo.com/vip'  
  >>> a.startswith (('http','ftp'))  
  True  

如果是列表或者字典,則報(bào)錯(cuò)

  >>> a='http://www.o2fo.com/vip'  
  >>> a.startswith (['http','ftp'])  
  Traceback (most recent call last):  
    File "", line 1in   
      a.startswith (['http','ftp'])  
  TypeError: startswith first arg must be str or a tuple of str, not list  
  >>>   

其實(shí),除了上面的方法, 也可以使用切片來(lái)實(shí)現(xiàn),只不過(guò)代碼看上去沒(méi)那么好看而已

  >>> a='http://www.o2fo.com/vip'  
  >>> a[0:4]=='http'  
  True  
  >>>   

當(dāng)然,我們也可以用正則表達(dá)式來(lái)做,但是理解上面就稍微難度有點(diǎn)。

  >>> import re  
  >>> url = 'http://www.python.org'  
  >>> re.match('http:|https:|ftp:', url)  
  05), 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.  
    
 >>>   


以上內(nèi)容是否對(duì)您有幫助:
在線(xiàn)筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)