James 发表于 2017-4-26 12:31:49

Python的字符串模板

  Python的字符串模板,可以无需记住类型的细节。
  subsitute()#严谨模式,在key缺少的情况下会报一个keyError的异常
  safe_subsitute()#在key缺少的情况下会原封不动的把字符串输出来
  


from string import Template
str = Template('to:${to}\ntitle:${title}\ncontext:${context}')
print(str.substitute(to = 'woxiaoe@gmail.com',title = 'hi',context = "hello world"),'\n')
print(str.safe_substitute(to = 'woxiaoe@gmail.com',title = 'hi'),'\n')#可以不初始化
print(str.substitute(title = 'hi',context = "hello world"))
  Output:
  

  to:woxiaoe@gmail.com
  title:hi
  context:hello world 
  to:woxiaoe@gmail.com
  title:hi
  context:${context} 
  Traceback (most recent call last):
  File "F:\study\ework\Python\src\day2_string.py", line 6, in <module>
  print(str.substitute(title = 'hi',context = "hello world"))
  File "D:\Python31\lib\string.py", line 156, in substitute
  return self.pattern.sub(convert, self.template)
  File "D:\Python31\lib\string.py", line 146, in convert
  val = mapping
  KeyError: 'to'
页: [1]
查看完整版本: Python的字符串模板