Python strip lstrip rstrip使用方法(字符串處理空格)


Python strip lstrip rstrip使用方法(字符串處理空格)

strip是trim掉字符串兩邊的空格。
lstrip, trim掉左邊的空格
rstrip, trim掉右邊的空格
strip ( s [ , chars ] )
Return a copy of the string with leading and trailing characters removed. If  chars is omitted or  None , whitespace characters are removed. If given and not  None chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on.

strip lstrip rstrip使用方法

Python中的strip用於去除字符串的首位字符,同理,lstrip用於去除左邊 的字符,rstrip用於去除右邊的字符。這三個函數都可傳入一個參數,指定要去除的首尾字符。注意的是,傳入的是一個字符數組,編譯器去除兩端所有相應 的字符,直到沒有匹配的字符,比如: 

theString = 'saaaay yes no yaaaass' 
print theString.strip('say') 
theString依次被去除首尾在['s','a','y']數組內的字符,直到字符在不數組內。所以,輸出的結果為: 
yes no 
比較簡單吧,lstrip和rstrip原理是一樣的。注意:當沒有傳入參數時,是默認去除首尾空格的。 

theString = 'saaaay yes no yaaaass' 
print theString.strip('say') 
print theString.strip('say ') #say后面有空格 
print theString.lstrip('say') 
print theString.rstrip('say') 
運行結果: 
yes no 
es no 
yes no yaaaass 
saaaay yes no
 
 
二:去掉中間空格
 
   按照文檔要求,應該可以去除string中的空格,但是結果如何呢?
  1. x = '    hello python   '   
  2. print  '|' , x.lstrip( ), '|' , x.rstrip( ), '|' , x.strip( ), '|'  
| hello python    |     hello python | hello python |
 
沒有成功!!!!!
   不知道那位仁兄能給出原因?謝謝
   有個笨方法:以空格split字符串,然后重新連接
   >>> x_list = x.split(' ')
   >>> y = ''.join(x_list)
   >>> print  '|' ,y,'|'

    | hellopython |
 
Success!!


免責聲明!

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



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