在本教程中,我们将讨论 Python 中的 4 种字符串格式化技术。

我们将介绍所有 4 种类型的方法并学习用例,以便您了解不同字符串格式化技术的基础知识。

简介

什么是字符串格式?好吧,我们可以称它为我们将内容动态注入字符串并返回该字符串的格式化版本的过程

有 4 种方式来执行字符串格式化,它们都彼此不同:

  • 使用 % 运算符(“旧式”)

  • 使用 format() 字符串方法

  • 使用字符串文字(f-string)

  • 使用字符串模板类

我们将看到上述方法的基本原理。


1.使用 %(模)运算符:

这种格式化字符串的方式,使用**%(模)运算符**。如果你知道 Python 中的算术运算符,那么你就会知道我们使用这个运算符来获得剩余的被除数。

我们在最古老的字符串格式化样式中使用的运算符相同。 模 (%) 运算符也称为“字符串格式化”或“字符串插值”运算符

这里是一个例子:

# An example to demonstrate the use of the operator for string formatting
name = "Python"
print("Hello, %s" %name)

# ----------------OR--------------
print("Hello, %s!" %'Geeks')

输出:

输出.png

我们使用格式说明符告诉 Python 您必须在该特定位置替换给定值。

我使用"%s"格式说明符在该特定位置插入字符串"Python"

我们有一些我们常用的格式说明符:

  • %s - 用于字符串

  • %d - 用于整数

  • %f - 用于浮点值

  • %b - 二进制格式

  • %e - 用于浮点指数

让我们看一下显示不同格式条件的示例。

示例 - 1:格式化整数值

print("I bought %d apples and %d oranges." %(6, 4))

输出:

example-1_Output.png

我们可以插入多个字符串,也可以使用变量在字符串中插入对象。

示例 - 2:

x = "car"
print("The dog %s down the %s." %('chased', x))

输出:

example-2 output.png

在单个字符串中使用多种格式转换类型。

示例 - 3:

name = "Yashwant"
print("My %s %s bought the car worth $%d." %('friend', name, 15000))

输出:

example-3 output.png

使用 % 运算符的浮点精度

print("The length of land is: %2.3f metres" %(85.52590))

输出:

浮点输出.png

现在你可能想知道,为什么我使用%2.3f

浮点数使用x.yf格式,其中x是字符串中的最小位数,yf表示必须在小数点后显示多少位

如果整数没有指定的位数,则可能会用空格填充。

print("The length of land is: %7.3f metres" %(85.52590))
print("The length of land is: %0.3f metres" %(85.52590))

输出:

浮点输出2.png

在这里,第一个打印语句用空格填充。您可以注意到两种结果的差异。

要了解更多信息,请点击此处。

zoz100036 * *

2.使用 format() 方法:

引入此方法是为了摆脱 % 运算符格式。此方法适用于更有效地处理复杂的字符串格式。

"%"运算符格式化相比,str.format()方法非常简单和快速,并且在 Python3 中引入。

在这种格式化技术中,格式化程序通过将占位符放在一对花括号"{ }"中并调用str.format()方法来工作。

句法:

"String 去 { } 和这里 { }".format("here" , "also")

这里是一个例子:

# Formatting using format() method

print("Hey {}, Welcome {}....".format('Geeks', 'here'))

输出:

format_output.png

让我们看一些例子

我们可以使用基于索引的定位在字符串中插入对象

示例 - 1:使用基于索引的定位

print("{1}, there's a {2} {0} ahead".format("error", "Caution", "Python"))

输出:

索引定位输出.png

示例 - 2:

print("Python: {x}, Inventor: {y}, Version: {z}".format(x=1991, 
                                                        y="Guido",
                                                        z=3.9))

输出:

example_2 output.png

示例 - 3:重用对象

print("The first {obj} was easy, the second {obj} was intermediate "
      "but the third {obj} was very tough.".format(obj="hurdle"))

输出:

example_3 output.png

使用.format()方法的浮点精度

print("The decimal number is: {0:1.3f}".format(54.123456, 23.5466))
print("The decimal number is: {1:1.3f}".format(54.123456, 23.5466))

输出:

浮点精度使用格式.png

我们已经看到了使用%运算符的浮点精度,其中格式为x.yf,但这里的情况有点不同。

在这里,Syntax 将是

{ [ 索引 ] : [ 宽度 ] 。 [ 精度 ] [ 类型 ] }

如果我们将{0:1.3f}分解为:

  • 0- 是索引值

  • 1- 是宽度

  • 3- 是精度或否。小数点后显示的位数

  • f- 是格式代码的类型

以下是我们可以与格式代码一起使用的常见类型:

  • "d" - 用于整数

  • "f" - 用于浮点数

  • "s" - 用于字符串

  • "e" - 用于指数格式的浮点数

  • "o" - 用于八进制数

  • "x" - 十六进制数

  • "b" - 用于二进制数

要了解更多信息,请点击此处。


3.使用 f-string(文字字符串插值):

文字字符串插值,一种格式化字符串的新机制,在PEP 498中引入。

这些字符串被称为 f-strings 因为它们的前导字符"f"用于表示字符串,这里 f - 代表 “格式化”字符串。

f 字符串是以字母"f"为前缀的字符串文字。

f-string 使用与str.format()相同的格式说明符迷你语言。

这是示例:

name = "Sachin"
print(f"Hi, I am {name}.")

输出:

f 字符串示例 output.png

让我们看看 f 字符串在不同条件下的用例:

示例 - 1:使用多个表达式

name = "Sachin"
x = 45
y = 12

print(f"Hi, I am {name} and I run {4*(x + y)} metres daily.")

输出:

f 字符串示例 1 output.png

**示例 - 2:在function中使用 f-string **

def write(name, say):
    return f"My name is {name} and I'm saying {say}."

output = write("Sachin", "Good luck")
print(output)

输出:

f 字符串示例 2 output.png

示例 - 3:在 f-string 中使用lambda表达式

print(f"Using lambda function: {(lambda x: x*13)(3)}")

输出:

f 字符串示例 3 output.png

** f 字符串中的浮点精度**

句法

{ 值:{ 宽度} 。 { 精确 } }

width = 5
precision = 7
value = 15.155245

print(f"The result is: {value:{width}.{precision}}")

输出:

f-string浮点精度输出.png

要了解更多信息,请点击此处。


4.字符串模板类

在这种方法中,我们在用{ }花括号括起来的占位符之前使用"$"

在这种格式化风格中,我们使用Template类来制作模板,一旦模板被创建,我们就可以通过调用两个方法来执行替换:

  • substitute():此方法返回一个新字符串,当映射的值被替换为模板中的占位符时会产生该字符串。如果映射中不存在占位符,则会引发 KeyError。

  • safe_substitute():这类似于substitute() 方法,除了从不引发KeyErrors(由于映射中缺少占位符)。当占位符丢失时,原始占位符将出现在结果字符串中。(来源)

查看示例以更好地理解:

from string import Template

name = "Sachin"
greet = "Welcome"

my_str = Template("Hello $x, $y here.")
print(my_str.substitute(x=name, y=greet))

输出:

模板类输出.png

这里"x""y"是以"$"为前缀的占位符被映射"name""greet"的值代替。

示例 - 1:提高KeyError

from string import Template

name = "Sachin"
greet = "Welcome"

my_str = Template("Hello $x, $y here.")
print(my_str.substitute(x=name))

输出:

模板类 KeyError.png

上面的代码片段引发了一个KeyError,因为我没有为占位符"$y"指定映射。但是如果我们使用"safe_substitute()"方法,那么它不会引发 KeyError

示例 - 2:使用safe_substitute方法

from string import Template

character = "Iron man"
name = "Stan Lee"
country = "USA"

my_str = Template("$x was created by $y for Marvel in $country")
print(my_str.safe_substitute(x=character, y=name))

输出:

模板类 safe_substitute.png

这里我没有为"$country"指定映射,但我仍然没有收到任何错误,因为我使用了"safe_substitute"方法。

要了解更多信息,请点击此处。


比较

from string import Template

character = "Iron man"
name = "Stan Lee"
country = "USA"

# Using % operator

print("%s was created by %s for Marvel in %s." %(character, name, country))

# Using format() method

print("{} was created by {} for Marvel in {}.".format(character, name, country))

# Using f-string

print(f"{character} was created by {name} for Marvel in {country}.")

# Using Template Class

my_str = Template("$x was created by $y for Marvel in $z.")
print(my_str.substitute(x=character, y=name, z=country))

输出:

比较输出.png


结论

到目前为止,我们得出的结论是,字符串格式化的所有方式都互不相同,每种方式都有独特的格式化风格。

创建了新技术和新方法来解决处理复杂格式的效率或能力不足的问题。

由于我们已经看到了所有类型的字符串格式化并进行了比较,我们可以为我们选择最好和最有效的字符串格式化技术。


目前为止就这样了

继续编码✌✌

Logo

学AI,认准AI Studio!GPU算力,限时免费领,邀请好友解锁更多惊喜福利 >>>

更多推荐