Python進階---python strip() split()函數實戰

來源:互聯網
上載者:User

標籤:9.1   name   xxx   win7   get   ora   alt   details   rate   

先看一個例子:
>>> ipaddr = 10.122.19.10  File "", line 1    ipaddr = 10.122.19.10                     ^SyntaxError: invalid syntax>>> ipaddr = "10.122.19.10">>> ipaddr.strip()‘10.122.19.10‘>>> ipaddr = ‘10.122.19.10‘>>> ipaddr.strip()‘10.122.19.10‘>>> ipaddr.split(‘.‘)[‘10‘, ‘122‘, ‘19‘, ‘10‘]>>> ipaddr.strip().split(‘.‘)[‘10‘, ‘122‘, ‘19‘, ‘10‘]>>> 

 

 python strip()函數 介紹

函數原型

聲明:s為字串,rm為要刪除的字元序列

s.strip(rm)        刪除s字串中開頭、結尾處,位於 rm刪除序列的字元

s.lstrip(rm)       刪除s字串中開頭處,位於 rm刪除序列的字元

s.rstrip(rm)      刪除s字串中結尾處,位於 rm刪除序列的字元

注意:

1. 當rm為空白時,預設刪除空白符(包括‘\n‘, ‘\r‘,  ‘\t‘,  ‘ ‘)

例如:

 

複製代碼 代碼如下:
>>> a = ‘     123‘>>> a.strip()‘123‘>>> a=‘\t\tabc‘‘abc‘>>> a = ‘sdff\r\n‘>>> a.strip()‘sdff‘

 

 

2.這裡的rm刪除序列是只要邊(開頭或結尾)上的字元在刪除序列內,就刪除掉。

例如 :

 

複製代碼 代碼如下:
>>> a = ‘123abc‘>>> a.strip(‘21‘)‘3abc‘   結果是一樣的>>> a.strip(‘12‘)‘3abc‘

 

Python Split函數的用法總結(  

字串的split用法

說明:
Python中沒有字元類型的說法,只有字串,這裡所說的字元就是只包含一個字元的字串!!!
這裡這樣寫的原因只是為了方便理解,僅此而已。

1.按某一個字元分割,如‘.’

1 str = (‘www.google.com‘)2 print str3 str_split = str.split(‘.‘)4 print str_split

 

 

結果如下:



2.按某一個字元分割,且分割n次。如按‘.’分割1次

1 str = (‘www.google.com‘)2 print str3 str_split = str.split(‘.‘,1)4 print str_split

 

結果如下:

 

3.按某一字串分割。如:‘||’

1 str = (‘WinXP||Win7||Win8||Win8.1‘)2 print str3 str_split = str.split(‘||‘)4 print str_split
 

結果如下:

 

4.按某一字串分割,且分割n次。如:按‘||’分割2次

1 str = (‘WinXP||Win7||Win8||Win8.1‘)2 print str3 str_split = str.split(‘||‘,2)4 print str_split
結果如下:

 

5.按某一字元(或字串)分割,且分割n次,並將分割的完成的字串(或字元)賦給新的(n+1)個變數。(註:見開頭說明)
如:按‘.’分割字元,且分割1次,並將分割後的字串賦給2個變數str1,str2

1 url = (‘www.google.com‘)2 str1, str2 = url.split(‘.‘, 1)3 print str14 print str2
 結果如下:

 

一個正則匹配的例子:

>>> str="xxxxxxxxxxxx5 [50,0,50]>,xxxxxxxxxx"

>>> lst = str.split("[")[1].split("]")[0].split(",")

>>> print lst

[‘50‘, ‘0‘, ‘50‘]

分解如下

>>> list =str.split("[") 按照左邊分割

>>> print list

[‘xxxxxxxxxxxx5 ‘, ‘50,0,50]>,xxxxxxxxxx‘]

>>> list =str.split("[")[1].split("]")  包含的再按右邊分割

再對所要的字串按照分割副  存放在列表中

>>> list

[‘50,0,50‘, ‘>,xxxxxxxxxx‘]

 

>>> str.split("[")[1].split("]")[0]

‘50,0,50‘

>>> str.split("[")[1].split("]")[0].split(",")

[‘50‘, ‘0‘, ‘50‘]

 

轉自:http://blog.csdn.net/feeltouch/article/details/49404671

Python進階---python strip() split()函數實戰(轉)

聯繫我們

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