是否有一个与Ruby的字符串插值等效的Python?

问题:是否有一个与Ruby的字符串插值等效的Python?

Ruby示例:

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

对我而言,成功的Python字符串连接似乎很冗长。

Ruby example:

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

The successful Python string concatenation is seemingly verbose to me.


回答 0

Python 3.6将添加与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中的字符串插值。第一个操作数是要内插的字符串,第二个操作数可以具有不同的类型,包括“映射”,将字段名称映射到要内插的值。在这里,我使用了局部变量字典locals()来映射字段名称name为它的值作为局部变量。

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

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 3.6 will add literal string interpolation similar to Ruby’s string interpolation. Starting with that version of Python (which is scheduled to be released by the end of 2016), you will be able to include expressions in “f-strings”, e.g.

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

Prior to 3.6, the closest you can get to this is

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

The % operator can be used for string interpolation in Python. The first operand is the string to be interpolated, the second can have different types including a “mapping”, mapping field names to the values to be interpolated. Here I used the dictionary of local variables locals() to map the field name name to its value as a local variable.

The same code using the .format() method of recent Python versions would look like this:

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

There is also the string.Template class:

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

回答 1

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

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

Since Python 2.6.X you might want to use:

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

回答 2

我开发了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}."

I’ve developed the interpy package, that enables string interpolation in Python.

Just install it via pip install interpy. And then, add the line # coding: interpy at the beginning of your files!

Example:

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

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

回答 3

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’s string interpolation is similar to C’s printf()

If you try:

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

The tag %s will be replaced with the name variable. You should take a look to the print function tags: http://docs.python.org/library/functions.html


回答 4

按照PEP 498的规定,Python 3.6包含字符串插值。您将可以执行以下操作:

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

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

String interpolation is going to be included with Python 3.6 as specified in PEP 498. You will be able to do this:

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

Note that I hate Spongebob, so writing this was slightly painful. :)


回答 5

你也可以有这个

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

You can also have this

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

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:性能可能有问题。这对于本地脚本很有用,而不对生产日志有用。

重复的:

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)

Usage:

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: performance may be a problem. This is useful for local scripts, not for production logs.

Duplicated:


回答 7

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

For old Python (tested on 2.4) the top solution points the way. You can do this:

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()

And you get

d: 1 f: 1.1 s: s

回答 8

Python 3.6和更高版本具有使用f字符串的文字字符串插值

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

Python 3.6 and newer have literal string interpolation using f-strings:

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