python模板字符串和格式化字符串

模板字符串:用string模块里的Template

Template()里面把字符串中某个值用设置变量${key}的方式先写好,然后在substitute()的方式把变量用其他值代替,就完成了字符串的替换

>>> from string import Template

>>> a=Template('would it be the ${key1} when we meet in ${key2}')

>>> a.substitute(key1='same',key2='heaven')
'would it be the same when we meet in heaven'

格式化字符串:用%s

在字符串中某个需要后期替换的字符,先用%s代替,然后在字符串外边再用%()把字符串中的%换成目标字符串,就实现了字符串格式化

>>> "would it be the %s when we meet in %s"%('same','heaven')
'would it be the same when we meet in heaven'

原文地址:https://www.cnblogs.com/xiaxiaoxu/p/9744228.html