是否有与 Ruby 的字符串插值等效的 Python? [英] Is there a Python equivalent to Ruby's string interpolation?

查看:52
本文介绍了是否有与 Ruby 的字符串插值等效的 Python?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ruby 示例:

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

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

The successful Python string concatenation is seemingly verbose to me.

推荐答案

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

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}.")

在 3.6 之前,最接近此的是

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

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

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.

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

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

还有 string.Template 类:

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

这篇关于是否有与 Ruby 的字符串插值等效的 Python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆