• python 字符串使用技巧


    1,变编译时字符串连接,第一种是正常(‘\’),第二种是不成用的。

    s1="hello world \
       !!!"
       
    print 's1: ',s1
    
    
    s2="hello world" "!"  "!!! " ' I love you'
       
    print 's2: ',s2
    

      

    s1:  hello world    !!!
    s2:  hello world!!!!  I love you

    2 字符串模板

    1 from string import Template
    2 s=Template('I am ${name}, I\'m ${age} years old!')
    3 
    4 print "name,age都给定的substitute函数结果: ", s.substitute(name='TianMG', age=26)
    5 
    6 print "只给name的safe_substitute函数结果,不会报错,原封不动的显示字符串:", s.safe_substitute(name='TianMG')
    7 
    8 print "只给name的substitute函数结果,报KeyError错误:", s.substitute(name='TianMG')

    结果:

    name,age都给定的substitute函数结果:  I am TianMG, I'm 26 years old!
    只给name的safe_substitute函数结果,不会报错,原封不动的显示字符串: I am TianMG, I'm ${age} years old!
    只给name的substitute函数结果,报KeyError错误:
        debugger.run(setup['file'], None, None)
      File "D:\Program Files\MyEclipse\Common\plugins\org.python.pydev_2.7.3.2013031601\pysrc\pydevd.py", line 1090, in run
        pydev_imports.execfile(file, globals, locals) #execute the script
      File "E:\Workspaces\python\MyTest\iterTest.py", line 37, in <module>
        print "只给name的safe_substitute函数结果,报KeyError错误:", s.substitute(name='TianMG')
      File "D:\Python27\lib\string.py", line 172, in substitute
        return self.pattern.sub(convert, self.template)
      File "D:\Python27\lib\string.py", line 162, in convert
        val = mapping[named]
    KeyError: 'age'
  • 相关阅读:
    团队第二次作业
    重载和多态
    团队第一次作业
    结对编程
    java处理数字字符串每5个数字为一组进行拆分,保留逗号。不足5个的也存为一组。
    POI & easyExcel快速使用
    Access denied for user 'root'@'localhost' (using password: YES) 解决方法
    快速理解 并发,并行,同步,异步
    Spring Tools Suite 安装于基本使用
    Mysql 数据备份与恢复
  • 原文地址:https://www.cnblogs.com/TianMG/p/3098437.html
Copyright © 2020-2023  润新知