有没有一个Python等价于Ruby的字符串插值?

2024-04-20 06:46:49 发布

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

Ruby示例:

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

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


Tags: the字符串namein示例rubyunderwho
3条回答

由于Python2.6.X,您可能需要使用:

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

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

Python 3.6将添加类似于Ruby字符串插值的literal string interpolation。从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()))

还有^{}类:

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

相关问题 更多 >