常用的方法是
format()函数:
>>> s = "This is an {example} with {vars}".format(vars="variables", example="example")>>> s'This is an example with variables'
它可以与多行格式字符串一起正常工作:
>>> s = '''... This is a {length} example.... Here is a {ordinal} line.... '''.format(length='multi-line', ordinal='second')>>> print(s)This is a multi-line example.Here is a second line.
您还可以传递带有变量的字典:
>>> d = { 'vars': "variables", 'example': "example" }>>> s = "This is an {example} with {vars}">>> s.format(**d)'This is an example with variables'
在语法上,最接近您要求的是模板字符串。例如:
>>> from string import Template>>> t = Template("This is an $example with $vars")>>> t.substitute({ 'example': "example", 'vars': "variables"})'This is an example with variables'
我应该补充一点,尽管该
format()功能更为常见,因为它易于使用并且不需要导入行。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)