python- strip lstrip rstrip

Python中的strip用於去除字符串的首位字符,同理,lstrip用於去除左邊的字符,rstrip用於去除右邊的字符。這三個函數都可傳入一個參數,指定要去除的首尾字符。注意的是,傳入的是一個字符數組,編譯器去除兩端所有相應的字符,直到沒有匹配的字符,比如:
[python] view plaincopy
  1. theString = 'saaaay yes no yaaaass'  
  2. print theString.strip('say')   
theString依次被去除首尾在['s','a','y']數組內的字符,直到字符在不數組內。所以,輸出的結果爲: 
yes no (注意yes和no的前後分別有空格,所以到那就暫停了)

比較簡單吧,lstrip和rstrip原理是一樣的。注意:當沒有傳入參數時,是默認去除首尾空格的。 

[python] view plaincopy
  1. theString = 'saaaay yes no yaaaass'  
  2. print theString.strip('say')  
  3. print theString.strip('say '#say後面有空格  
  4. print theString.lstrip('say')  
  5. print theString.rstrip('say')   
運行結果: 
yes no 
es no 
yes no yaaaass 
saaaay yes no


發佈了31 篇原創文章 · 獲贊 5 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章