您的位置:首页 > 编程语言 > Python开发

Python零碎知识(1):strip lstrip rstrip使用方法

2014-05-09 12:16 615 查看
一、原理介绍:

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=False
15     while not done:
16         chosen=False
17         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]' %choice
23             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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: