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

标签 python string-interpolation language-comparisons

Ruby 示例:

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

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

最佳答案

Python 3.6 将添加 literal string interpolation类似于 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())

% 运算符可用于 string interpolation在 Python 中。第一个操作数是要插值的字符串,第二个操作数可以有不同的类型,包括“映射”,将字段名称映射到要插值的值。这里我使用了局部变量字典 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 - 是否有与 Ruby 的字符串插值等效的 Python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4450592/

相关文章:

用于函数输出的 PHP 插值字符串

go - 在反引号字符串中添加字符串插值

python - 如何用纯 Python 表达这个 Bash 命令

php - Python 的 pass 语句在 PHP 中的等价物是什么?

c# - F# vs Haskell vs Lisp——学习哪种语言?

python - 如何使用 Python 将 BeautifulSoup.Tag 设置为 Gtk3 中的标签

python - 如何使用 grequest 从多个 url 打印相同的字典对象?

angular - 使用反引号运算符在字符串中进行插值

Python - 绘制大量线条

python - 编写好的 Python 代码的技巧