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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4450592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:48:06  来源:igfitidea点击:

Is there a Python equivalent to Ruby's string interpolation?

pythonstring-interpolationlanguage-comparisons

提问by Caste

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.

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

采纳答案by Sven Marnach

Python 3.6 will add literal string interpolationsimilar 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.

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

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

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

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

The %operator can be used for string interpolationin 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 nameto its value as a local variable.

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

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

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

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

There is also the string.Templateclass:

还有一个string.Template类:

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

回答by Oleiade

Python's string interpolation is similar to C's printf()

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

If you try:

如果你试试:

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

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

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

回答by EinLama

Since Python 2.6.X you might want to use:

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

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

回答by Paulo Cheque

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.

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

Duplicated:

重复:

回答by Quan To

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

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

回答by Syrus Akbary Nieto

I've developed the interpypackage, that enables string interpolation in Python.

我开发了interpy包,它可以在 Python进行字符串插值

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

只需通过pip install interpy. 然后,# coding: interpy在文件的开头添加这一行!

Example:

例子:

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

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

回答by kirbyfan64sos

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

根据 PEP 498 的规定,字符串插值将包含在 Python 3.6 中。你将能够做到这一点:

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. :)

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

回答by Michael Fox

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

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

And you get

你得到

d: 1 f: 1.1 s: s

回答by Alejandro Silva

Python 3.6 and newer have literal string interpolationusing f-strings:

Python 3.6 和更新版本使用 f 字符串进行文字字符串插值

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