Python的字符串模板

Python的字符串模板,可以无需记住类型的细节。

subsitute()#严谨模式,在key缺少的情况下会报一个keyError的异常

safe_subsitute()#在key缺少的情况下会原封不动的把字符串输出来

from string import Template
str = Template('to:${to}\ntitle:${title}\ncontext:${context}')
print(str.substitute(to = '[email protected]',title = 'hi',context = "hello world"),'\n')

print(str.safe_substitute(to = '[email protected]',title = 'hi'),'\n')#可以不初始化
print(str.substitute(title = 'hi',context = "hello world"))

 Output:

to:[email protected]

title:hi

context:hello world 

 

to:[email protected]

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[named]

KeyError: 'to'


你可能感兴趣的:(python,F#,Gmail)