字符串插值是将字符串中的占位符替换为局域变量的过程。许多编程语言都可以做到,比如 Scala:
// Scale 2.10+
var name = "John";
println(s"My name is $name")
>>> My name is John
Perl:
my $name = "John";
print "My name is $name";
>>> My name is John
CoffeeScript:
name = "John"
console.log "My name is #{name}"
>>> My name is John
… 还有很多。
乍看之下,似乎不大可能使用 Python 实现字符串插值,但实际上,我们只需要两行代码就可以实现。
首先,让我们从基础开始说起。通常我们构建一个复杂的 Python 字符串时都会使用 format 函数:
print "Hi, I am {} and I am {} years old".format(name, age)
>>> Hi, I am John and I am 26 years old
可以看出,format 的实现比字符串连接看起来整洁许多:
print "Hi, I am " + name + " and I am " + str(age) + " years ol