Python

Python基础(18) - 字符串格式化与模板字符串方法

2020-02-27  本文已影响0人  xianling_he

字符串格式化的各种方法

  1. 使用%格式化
  2. 模板字符串
  3. 字符串的format方法
  4. fstring
from string import Template

temp1 = Template('$s 是我喜欢的编程语言,$s 是容易学习,而且强大的语言') # 模板字符串

print(temp1.substitute(s = 'Python'))
image.png
  1. 如果占位符与后面的英文有冲突,就将占位符使用大括号{}进行括起来,用来区分占位符与英文
temp2 = Template('$who is Joke')
print(temp2.substitute(who = 'Joke'))
image.png
temp2 = Template('${w} who is Joke')
print(temp2.substitute(w = 'Joke!'))
image.png
temp3 = Template('$yuan 元等于 $dollar 美元$$')
print(temp3.substitute(yuan='1',dollar ='7'))
image.png
temp3 = Template('$yuan 元等于 $dollar 美元$$')
data = {}
data['yuan'] = 10
data['dollar'] = 70
print(temp3.substitute(data))
image.png

总结

1.模板字符串是Template类封装的一个字符串,可以用美元符号$执行占位符
2.使用substitute方法替换这些占位符

加油 2020-2-27

上一篇 下一篇

猜你喜欢

热点阅读