python3.4學習筆記(二十) python strip()函數 去空格\n\r\t函數的用法


python3.4學習筆記(二十) python strip()函數 去空格\n\r\t函數的用法

在Python中字符串處理函數里有三個去空格(包括'\n', '\r', '\t', ' ')的函數:

strip 同時去掉左右兩邊的空格
lstrip 去掉左邊的空格
rstrip 去掉右邊的空格

具體示例如下:
>>>a=" gho stwwl "
>>>a.lstrip() 'gho stwwl '
>>>a.rstrip() ' gho stwwl'
>>>a.strip() 'gho stwwl'

聲明: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'

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2024 CODEPRJ.COM