Python strip lstrip rstrip使用方法(字符串處理空格)
strip是trim掉字符串兩邊的空格。
lstrip, trim掉左邊的空格
rstrip, trim掉右邊的空格
lstrip, trim掉左邊的空格
rstrip, trim掉右邊的空格
| strip ( | s [ , chars ] ) |
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
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中的空格,但是結果如何呢?
- x = ' hello python '
- print '|' , x.lstrip( ), '|' , x.rstrip( ), '|' , x.strip( ), '|'
沒有成功!!!!!
不知道那位仁兄能給出原因?謝謝
有個笨方法:以空格split字符串,然后重新連接
>>> x_list = x.split(' ')
>>> y = ''.join(x_list)
>>> print '|' ,y,'|'
>>> y = ''.join(x_list)
>>> print '|' ,y,'|'
| hellopython |
Success!!
