Python 中的字符串插值

字符串插值是指在字符串中插入变量值代替占位符的技术。使用字符串插值,可以在字符串中动态插入值。

在 Python 中,我们可以通过四种方式来执行字符串插值,即取模 (%)、format() 方法、格式化字符串和模板类。在本文中,我们将详细了解这些方法。

在 Python 中使用模 (%) 进行字符串插值

我们可以使用模数 (%) 在 Python 中格式化字符串。这种方法类似于 C 编程语言中的 printf()

以下是我们可以在字符串中使用的占位符进行格式化。

%d = Integer
%f = Float
%s = String
%x = Hexadecimal
%o = Octal

请注意,必须在字符串中的字符之前放置一个模字符才能被视为占位符。以下是使用模数 (%) 的语法。

"<string with placeholders>" % (<comma separated values or variables>)

现在,我们完成了一些简短的介绍;让我们通过一些例子来了解如何实际使用这个概念。请参阅以下 Python 代码。

a = 2000
b = "Hi"
c = "Python"
d = True
e = 3.14
print("%d + 1000 = 3000" % (a))
print("%s is a web framework written in %s" % ("Django", c))
print("[%d, %s, %s, %s, %f]" % (a, b, c, d, e))
print("%s! My favourite programming language is %s" % (b, c))
print("The value of PI or π: %f" % (e))

输出:

2000 + 1000 = 3000
Django is a web framework written in Python
[2000, Hi, Python, True, 3.140000]
Hi! My favourite programming language is Python
The value of PI or π: 3.140000

请注意如何在字符串中使用占位符进行格式化,以及什么占位符用于什么类型的值。

在 Python 中使用 format() 方法进行字符串插值

format() 方法可用于在 Python 中格式化字符串。此方法与前一种方法类似,但在这里,{} 充当每种类型值的占位符。

以下是 format() 方法的语法。

"<string with placeholdes>".format(<comma separated values and variables>)

请参考以下 Python 代码,借助一些相关示例更好地理解这个概念。

a = 2000
b = "Hi"
c = "Python"
d = True
e = 3.14
print("{} + 1000 = 3000".format(a))
print("{} is a web framework written in {}".format("Django", c))
print("[{}, {}, {}, {}, {}]".format(a, b, c, d, e))
print("{}! My favourite programming language is {}".format(b, c))
print("The value of PI or π: {}".format(e))

输出:

2000 + 1000 = 3000
Django is a web framework written in Python
[2000, Hi, Python, True, 3.14]
Hi! My favourite programming language is Python
The value of PI or π: 3.14

在 Python 中使用格式化字符串进行字符串插值

格式化字符串是 Python 中唯一的字符串。当以 f 字符为前缀时,常规字符串是格式化字符串。

格式化字符串也称为 f 字符串。这些字符串用于在字符串中动态插入变量和对象的字符串表示形式。

我们可以在字符串中添加 {},在这些块中,我们可以添加返回一些值的变量或逻辑。

以下是格式化字符串的语法。

f"{<variable>} {<variable>} {<variable>}"

让我们通过一些相关的例子来理解这个概念。请参阅以下 Python 代码。

def hello():
    return "Hello"

a = 2000
b = "Hi"
c = "Python"
d = True
e = 3.14
print(f"{a} + 1000 = 3000")
print(f"Django is a web framework written in {c}")
print(f"[{a}, {b}, {c}, {d}, {e}]")
print(f"{hello()}! My favourite programming language is {c}")
print(f"The value of PI or π: {e}")
print(f"1000 + 2000 = {1000 + 2000}")
print(f"10 * 20 - 25 = {10 * 20 - 25}")

输出:

2000 + 1000 = 3000
Django is a web framework written in Python
[2000, Hi, Python, True, 3.14]
Hello! My favourite programming language is Python
The value of PI or π: 3.14
1000 + 2000 = 3000
10 * 20 - 25 = 175

在 Python 中使用模板类进行字符串插值

Python 有一个内置模块 string,一个允许我们创建动态字符串的类 Template。使用这种方法,我们可以执行基于 $ 的替换。

例如,对于 Hello $name 字符串,name 是一个变量,我们可以为这个变量提供一个值。我们可以使用 Template 类的 substitute() 来替换值。

此方法接受一个字典,其中模板字符串的变量是键,它们指向值。除了使用字典,我们还可以提供关键字参数。

请注意,如果找不到密钥,Python 解释器将抛出一个 KeyError。为避免这种情况,可以确保字典中存在所需的键,或者使用 safe_substitute() 方法使该占位符的字符串保持不变。

现在我们已经完成了一些理论,让我们借助一些相关示例来理解这个概念。请参阅以下 Python 代码。

from string import Template

def pi():
    return 3.14
    
t1 = Template("$a + 1000 = 3000")
t2 = Template("$package is a web framework written in $language")
t3 = Template("$greeting! My favourite programming language is $language")
t4 = Template("[$a, $b, $c, $d, $e]")
t5 = Template("The value of PI or π: $pi")
print(t1.substitute({ "a": 2000 }))
print(t2.substitute({ "package": "Flask", "language": "Python" }))
print(t3.substitute({ "greeting": "Hey", "language": "Python" }))
print(t4.substitute(a = 2000, b = "Hi", c = "Python", d = True, e = 999.909))
print(t5.substitute(pi = pi()))

输出:

2000 + 1000 = 3000
Flask is a web framework written in Python
Hey! My favourite programming language is Python
[2000, Hi, Python, True, 999.909]
The value of PI or π: 3.14

请参考以下 Python 代码以使用 safe_substitute() 方法。

from string import Template

def pi():
    return 3.14
    
t1 = Template("$a + 1000 = 3000")
t2 = Template("$package is a web framework written in $language")
t3 = Template("$greeting! My favourite programming language is $language")
t4 = Template("[$a, $b, $c, $d, $e]")
t5 = Template("The value of PI or π: $pi")
print(t1.safe_substitute({ }))
print(t2.safe_substitute({ "package": "Flask" }))
print(t3.safe_substitute({ "language": "Python" }))
print(t4.safe_substitute(c = "Python", d = True, e = 999.909))
print(t5.safe_substitute())

输出:

$a + 1000 = 3000
Flask is a web framework written in $language
$greeting! My favourite programming language is Python
[$a, $b, Python, True, 999.909]
The value of PI or π: $pi