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

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

问题描述

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

string1 = gostring2 = 现在string3 = 很棒"""我会在那里 $string1我会去 $string2$string3"""

我想看看 Perl 中是否有类似于 $ 的东西来指示 Python 语法中的变量.

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

解决方案

常用的方式是format()函数:

<预><代码>>>>s = "这是一个带有 {vars} 的 {example}".format(vars="variables", example="example")>>>秒'这是一个带有变量的例子'

它适用于多行格式字符串:

<预><代码>>>>s = '''... 这是一个 {length} 示例.... 这是一个 {ordinal} 行.... '''.format(length='multi-line', ordinal='second')>>>印刷)这是一个多行示例.这是第二行.

你也可以传递一个带有变量的字典:

<预><代码>>>>d = { 'vars': "变量", 'example': "example" }>>>s = "这是一个带有 {vars} 的 {example}">>>s.format(**d)'这是一个带有变量的例子'

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

<预><代码>>>>从字符串导入模板>>>t = Template("这是一个带有 $vars 的 $example")>>>t.substitute({ 'example': "example", 'vars': "变量"})'这是一个带有变量的例子'

我应该补充一点,format() 函数更常见,因为它很容易获得并且不需要导入行.

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

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?

解决方案

The common way is the format() function:

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

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天全站免登陆