如何使用内联变量创建多行Python字符串? [英] How do I create a multiline Python string with inline variables?

查看:143
本文介绍了如何使用内联变量创建多行Python字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种在多行Python字符串中使用变量的干净方法.假设我想执行以下操作:

I am looking for a clean way to use variables within a multiline Python string. Say I wanted to do the following:

string1 = go
string2 = now
string3 = great

"""
I will $string1 there
I will go $string2
$string3
"""

我正在寻找Perl中是否有与$类似的东西来指示Python语法中的变量.

I'm looking to see if there is something similar to $ in Perl to indicate a variable in the Python syntax.

如果不是-用变量创建多行字符串的最干净方法是什么?

If not - what is the cleanest way to create a multiline string with variables?

推荐答案

常见的方法是format()函数:

>>> s = "This is an {example} with {vars}".format(vars="variables", example="example")
>>> s
'This is an example with variables'

它可以与多行格式的字符串一起正常工作:

It works fine with a multi-line format string:

>>> 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.

您还可以传递带有变量的字典:

You can also pass a dictionary with variables:

>>> d = { 'vars': "variables", 'example': "example" }
>>> s = "This is an {example} with {vars}"
>>> s.format(**d)
'This is an example with variables'

(在语法上)最接近您要求的是模板字符串.例如:

The closest thing to what you asked (in terms of syntax) are template strings. For example:

>>> 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()函数更常见,因为它易于使用并且不需要导入行.

I should add though that the format() function is more common because it's readily available and it does not require an import line.

这篇关于如何使用内联变量创建多行Python字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆