Python零碎知识(1):strip lstrip rstrip使用方法
来源:互联网 发布:识时务,知进退,善其身 编辑:程序博客网 时间:2024/05/21 10:52
一、原理介绍:
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()
0 0
- Python零碎知识(1):strip lstrip rstrip使用方法
- Python strip lstrip rstrip使用方法
- Python strip lstrip rstrip使用方法
- Python strip lstrip rstrip使用方法
- Python strip lstrip rstrip使用方法
- Python strip lstrip rstrip使用方法
- Python strip lstrip rstrip使用方法
- Python strip lstrip rstrip使用方法
- Python strip lstrip rstrip使用方法
- Python strip lstrip rstrip使用方法
- Python strip lstrip rstrip使用方法
- Python strip lstrip rstrip使用方法
- Python strip lstrip rstrip使用方法
- Python strip lstrip rstrip使用方法
- Python strip lstrip rstrip使用方法
- Python strip lstrip rstrip使用方法
- strip()、 lstrip()、 rstrip()使用方法
- Python 中的strip lstrip rstrip使用方法
- android Google Map API V2 (key 申请)
- HDU 1004 Let the Balloon Rise
- 独立完成!
- Python零碎知识(2):强大的zip
- 从cmd启动mysql
- Python零碎知识(1):strip lstrip rstrip使用方法
- HDU 1003 MAX SUM
- python零碎知识(5):有关正则表达式
- 关于客户端用ASP参生报表
- HDU 1005 Number Sequence
- python零碎知识(8):UserDict 类
- sqlserver视图
- 常见 Datagrid 错误
- Python零碎知识(3):对文件的基本操作