python strip() and split() 函數

先看一個例子:

>>> 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')

Python Split函數的用法總結

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

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

>>> str = ('www.google.com')
>>> print str
www.google.com
>>> str_split= str.split('.')
>>> print str_split
['www', 'google', 'com']

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

>>> str_split = str.split('.',1)
>>> print str_split
['www', 'google.com']

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

>>> str = ('WinXP||Win7||Win8||Win8.1')
>>> str_split = str.split('||')
>>> print str_split
['WinXP', 'Win7', 'Win8', 'Win8.1']


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章