您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何使用内联变量创建多行Python字符串?

如何使用内联变量创建多行Python字符串?

常用的方法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()功能更为常见,因为它易于使用并且不需要导入行。

python 2022/1/1 18:44:35 有296人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶