一、原理介紹:
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
註:這段解釋來自:(pylemon's notebook):http://www.cnblogs.com/pylemon/archive/2011/05/18/2050179.html
 二、實際應用
這裡舉一個demo,用於在pythonIED中控制輸出菜單,選擇相應的選項,操作對應的操作。如下:
假設程式中已經存在newUser和oldUser兩個函數,這裡我只貼出了主要部分
 1 #菜單控制介面 2 def showmenu(): 3     prompt='''    4     ************************* 5     Welcome to Python System! 6     -------------------------                                      7     |(N)ew User Login        | 8     |(L)ogin your system     | 9     |(Q)uit                  |10     -------------------------11     Enter Choice:12     **************************13     '''14     done=False15     while not done:16         chosen=False17         while not chosen:18             try:19                 choice=raw_input(prompt).strip()[0].lower() #取輸入的字串第一個字元20             except(EOFError,KeyboardInterrupt):21                 choice='q'                                  #拋出異常22             print '\n You picked:[%s]' %choice23             if choice not in 'nlq':                         #判斷輸出字串中首字元是否屬於'nlq'24                 print 'Invalid option,tyr again'25             else:26                 chosen=True                                 #一切正常則跳出迴圈27         #根據輸入資訊進行控制28         if choice=='q':done=True                            #如果輸入'q'則跳出整個迴圈,不再執行29         if choice=='n':newUser()                            #如果輸入'n'則調用使用者註冊函數30         if choice=='l':oldUser()                            #如果輸入'l'則調用使用者登陸函數31 32 #主程式33 if __name__=="__main__":34     showmenu()
註:請注意紅色部分代碼