天天看點

Python天天美味(6) - strip lstrip rstrip

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

Python天天美味(6) - strip lstrip rstrip

theString = 'saaaay yes no yaaaass'

Python天天美味(6) - strip lstrip rstrip

print theString.strip('say')

theString依次被去除首尾在['s','a','y']數組内的字元,直到字元在不數組内。是以,輸出的結果為:

yes no

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

Python天天美味(6) - strip lstrip rstrip
Python天天美味(6) - strip lstrip rstrip
Python天天美味(6) - strip lstrip rstrip

print theString.strip('say ') #say後面有空格

Python天天美味(6) - strip lstrip rstrip

print theString.lstrip('say')

Python天天美味(6) - strip lstrip rstrip

print theString.rstrip('say')

運作結果:

Python天天美味(6) - strip lstrip rstrip

 yes no 

Python天天美味(6) - strip lstrip rstrip

es no

Python天天美味(6) - strip lstrip rstrip

 yes no yaaaass

Python天天美味(6) - strip lstrip rstrip

saaaay yes no

<a target="_blank" href="http://www.cnblogs.com/coderzh/archive/2008/05/03/1180584.html">Python 天天美味(8) - 字元串中的字元倒轉</a>

..

本文轉自CoderZh部落格園部落格,原文連結:http://www.cnblogs.com/coderzh/archive/2008/05/02/1179725.html,如需轉載請自行聯系原作者