在Python中嵌入一个表达式有什么等价性?(例如Ruby中的“#{expr}”)

2024-06-01 01:23:52 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,我想用嵌入的表达式创建一个字符串块。
在Ruby中,代码如下所示:

def get_val
  100
end

def testcode
s=<<EOS

This is a sample string that references a variable whose value is: #{get_val}
Incrementing the value: #{get_val + 1}

EOS
  puts s
end

testcode

Tags: sample字符串代码getstringisvalue表达式
3条回答

如果您需要的不仅仅是^{}^{}提供的简单字符串格式,则可以使用^{}模块插入Python表达式:

from templet import stringfunction

def get_val():
    return 100

@stringfunction
def testcode(get_val):
    """
    This is a sample string
    that references a function whose value is: ${ get_val() }
    Incrementing the value: ${ get_val() + 1 }
    """

print(testcode(get_val))

输出

^{pr2}$

Python Templating with @stringfunction。在

作为一个C和Ruby程序员,我喜欢经典的printf式的方法:

>>> x = 3
>>> 'Sample: %d' % (x + 1)
'Sample: 4'

或者在有多个参数的情况下:

^{pr2}$

我已经感觉到人们会因为这个而打我。然而,我发现这一点特别好,因为它在Ruby中的工作方式是一样的。在

使用格式方法:

>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c')  # 2.7+ only
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc')      # unpacking argument sequence
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad')   # arguments' indices can be repeated
'abracadabra'

按名称设置格式:

^{pr2}$

相关问题 更多 >