gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:33:46 27 4
gpt4 key购买 nike

我正在寻找一种在多行 Python 字符串中使用变量的简洁方法。假设我想做以下事情:

string1 = go
string2 = now
string3 = great

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

我正在寻找是否有类似于 Perl 中的 $ 的东西来指示 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'

最接近您所问的内容(就语法而言)是template strings .例如:

>>> 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 - 如何使用内联变量创建多行 Python 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10112614/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com