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


    转载:http://www.cnblogs.com/BeginMan/archive/2013/03/14/2958985.html

    一、原理介绍:

    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 '
     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()
  • 相关阅读:
    android 蓝牙各种UUID (转)
    Linux下Shell重定向
    linux命令学习笔记——tee命令
    正则表达式之正向预查和反向预查
    shell常用正则表达式
    saltstack知识点
    linux命令学习笔记——ldd命令
    shell中${ } 的一些特异功能
    linux命令学习笔记——nl命令
    linux命令学习笔记——losetup命令:设置循环设备
  • 原文地址:https://www.cnblogs.com/sunshishi/p/4763467.html
Copyright © 2020-2023  润新知