zoukankan      html  css  js  c++  java
  • 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'
  • 相关阅读:
    python3爬虫 -----新浪微博(m)-------评论爬取
    hdu 5585
    Atcoder 092
    python3糗事爬取-------------------糗事百科
    python3爬虫 -----爬取职位招聘信息-------from腾讯社会招聘
    python3电影详细信息爬取-------------------电影天堂
    Python词云分析
    合并排序
    活动安排问题
    你好,2019!
  • 原文地址:https://www.cnblogs.com/TianMG/p/3098437.html
Copyright © 2011-2022 走看看