模板字符串:用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'

相关文章:

  • 2021-07-29
猜你喜欢
  • 2021-06-21
  • 2022-12-23
  • 2021-12-28
  • 2021-06-11
  • 2021-09-01
  • 2022-02-09
相关资源
相似解决方案