Python中是否存在与Ruby's字符串插值等效的函数?

Ruby的例子:

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

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

201860 次浏览

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

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中,%操作符可用于字符串插值。第一个操作数是要插入的字符串,第二个操作数可以有不同的类型,包括“mapping”,将字段名映射到要插入的值。这里我使用局部变量字典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"))

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

从Python 2.6开始。X你可能想用:

"my {0} string: {1}".format("cool", "Hello there!")
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:性能可能是个问题。这对本地脚本有用,对生产日志没用。

复制:

你也可以吃这个

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

我已经开发了人类学家包,即启用Python中的字符串插值

只要通过pip install interpy安装它。 然后,在文件的开头添加一行# coding: interpy !< / p >

例子:

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


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

字符串插值将是在PEP 498中指定的Python 3.6中包含。你可以这样做:

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

请注意,我讨厌海绵宝宝,所以写这篇文章有点痛苦。:)

对于旧的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

Python 3.6及更新版本使用f-strings拥有字面值字符串插值:

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