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'
原文地址:https://www.cnblogs.com/TianMG/p/3098437.html