f-string 高级字符串格式化
- f-string无法替换带有${name}的字符串,会保留
\$
def test_fstring():"""f-string,高级字符串格式化的方式"""s = "my name is {name}".format(name='李白')print(s)# 无法替换$s = "my name is ${name}".format(name='李白')print(s)
string Template模块
- Template()可以用作复杂的模板替换
from string import Templatedef test_template():"""string 模板的方式"""t = Template("my name is ${name}, ${age}")# 必须得同时赋值两个参数,否则报错s = t.substitute(name="李白", age="18")print(s)
def test_template_2():"""string 模板的方式"""t = Template("my name is ${name}, ${age}")# safe_substitute,允许赋值一个参数s = t.safe_substitute(name="李白")print(s)