Python中strip()、lstrip()、rstrip()用法詳解

來源:互聯網
上載者:User

標籤:rip   不為   注意   詳解   去除   nbsp   說明   去掉   ring   

Python中有三個去除頭尾字元、空白符的函數,它們依次為:
strip: 用來去除頭尾字元、空白符(包括\n、\r、\t、‘ ‘,即:換行、斷行符號、定位字元、空格)
lstrip:用來去除開頭字元、空白符(包括\n、\r、\t、‘ ‘,即:換行、斷行符號、定位字元、空格)
rstrip:用來去除結尾字元、空白符(包括\n、\r、\t、‘ ‘,即:換行、斷行符號、定位字元、空格)

注意:這些函數都只會刪除頭和尾的字元,中間的不會刪除。

用法分別為:
string.strip([chars])
string.lstrip([chars])
string.rstrip([chars])

參數chars是可選的,當chars為空白,預設刪除string頭尾的空白符(包括\n、\r、\t、‘ ‘)
當chars不為空白時,函數會被chars解成一個個的字元,然後將這些字元去掉。

它返回的是去除頭尾字元(或空白符)的string副本,string本身不會發生改變。

舉例說明如下:
1. 當chars為空白時,預設刪除空白符(包括‘\n‘, ‘\r‘, ‘\t‘, ‘ ‘)

>>> str = ‘ ab cd ‘>>> str‘ ab cd ‘>>> str.strip() #刪除頭尾空格‘ab cd‘>>> str.lstrip() #刪除開頭空格‘ab cd ‘>>> str.rstrip() #刪除結尾空格‘ ab cd‘

2.當chars不為空白時,函數會被chars解成一個個的字元,然後將這些字元去掉。

>>> str2 = ‘1a2b12c21‘>>> str2.strip(‘12‘) #刪除頭尾的1和2‘a2b12c‘>>> str2.lstrip(‘12‘) #刪除開頭的1和2‘a2b12c21‘>>> str2.rstrip(‘12‘) #刪除結尾的1和2‘1a2b12c‘

 

Python中strip()、lstrip()、rstrip()用法詳解

聯繫我們

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