有没有Python相当于Ruby的字符串插值?

时间:2010-12-15 13:50:58

标签: python string-interpolation language-comparisons

Ruby示例:

name = "Spongebob Squarepants"
puts "Who lives in a Pineapple under the sea? \n#{name}."

成功的Python字符串连接对我来说似乎很冗长。

9 个答案:

答案 0 :(得分:378)

Python 3.6将添加literal string interpolation,类似于Ruby的字符串插值。从该版本的Python(计划于2016年底发布)开始,您将能够在“f-strings”中包含表达式,例如

name = "Spongebob Squarepants"
print(f"Who lives in a Pineapple under the sea? {name}.")

在3.6之前,你可以得到最接近的是

name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? %(name)s." % locals())

%运算符可用于Python中的string interpolation。第一个操作数是要插值的字符串,第二个操作数可以有不同的类型,包括“映射”,将字段名称映射到要插值的值。在这里,我使用局部变量字典locals()将字段名称name映射到其值作为局部变量。

使用最新Python版本的.format()方法的相同代码如下所示:

name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? {name!s}.".format(**locals()))

还有string.Template类:

tmpl = string.Template("Who lives in a Pineapple under the sea? $name.")
print(tmpl.substitute(name="Spongebob Squarepants"))

答案 1 :(得分:134)

从Python 2.6.X开始,您可能想要使用:

"my {0} string: {1}".format("cool", "Hello there!")

答案 2 :(得分:32)

我开发了interpy包,在Python中启用字符串插值

只需通过pip install interpy安装即可。 然后,在文件的开头添加行# coding: interpy

示例:

#!/usr/bin/env python
# coding: interpy

name = "Spongebob Squarepants"
print "Who lives in a Pineapple under the sea? \n#{name}."

答案 3 :(得分:26)

字符串插值将是included with Python 3.6 as specified in PEP 498。你将能够做到这一点:

name = 'Spongebob Squarepants'
print(f'Who lives in a Pineapple under the sea? \n{name}')

请注意,我讨厌Spongebob,所以写这个有点痛苦。 :)

答案 4 :(得分:25)

Python的字符串插值类似于C的printf()

如果您尝试:

name = "SpongeBob Squarepants"
print "Who lives in a Pineapple under the sea? %s" % name

标记%s将替换为name变量。您应该查看打印功能标签:http://docs.python.org/library/functions.html

答案 5 :(得分:4)

您也可以拥有此

name = "Spongebob Squarepants"
print "Who lives in a Pineapple under the sea? \n{name}.".format(name=name)

http://docs.python.org/2/library/string.html#formatstrings

答案 6 :(得分:3)

import inspect
def s(template, **kwargs):
    "Usage: s(string, **locals())"
    if not kwargs:
        frame = inspect.currentframe()
        try:
            kwargs = frame.f_back.f_locals
        finally:
            del frame
        if not kwargs:
            kwargs = globals()
    return template.format(**kwargs)

用法:

a = 123
s('{a}', locals()) # print '123'
s('{a}') # it is equal to the above statement: print '123'
s('{b}') # raise an KeyError: b variable not found

PS:性能可能有问题。这对本地脚本很有用,而不适用于生产日志。

重复的:

答案 7 :(得分:2)

对于旧的Python(在2.4上测试),顶级解决方案指明了方向。你可以这样做:

import string

def try_interp():
    d = 1
    f = 1.1
    s = "s"
    print string.Template("d: $d f: $f s: $s").substitute(**locals())

try_interp()

你得到了

d: 1 f: 1.1 s: s

答案 8 :(得分:0)

Python 3.6及更高版本的literal string interpolation使用f字符串:

name='world'
print(f"Hello {name}!")