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

Posted 夏晓旭

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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‘



以上是关于python模板字符串和格式化字符串的主要内容,如果未能解决你的问题,请参考以下文章

python字符串格式化: %操作符 {}操作符

python格式化输出(转)

python格式化字符

Python % 格式化字符串

在 django 模板中使用 python 字符串格式化

python 字符串格式化(%)