跳至主要内容

Python 字符串 format() 教程

了解 Python 中的字符串格式化。
· 5分钟 阅读

使用 AI 探索

字符串格式化也称为字符串插值。它是将自定义字符串或变量插入到预定义文本中的过程。

custom_string = "String formatting"
print(f"{custom_string} is a powerful technique")
String formatting is a powerful technique

作为一名数据科学家,您会用它在图表中插入标题、显示消息或错误,或向函数传递语句。

格式化方法

  • 位置格式化
  • 格式化字符串字面量
  • 模板方法

String.Format 方法

我们在文本中放置由一对花括号定义的占位符。调用字符串的点号 format 方法,然后将所需的值传入该方法。该方法按出现的顺序用值替换占位符:

'text{}'.format(value)

位置格式化

我们定义一个字符串并插入两个占位符。向该方法传递两个字符串,将得到以下输出:

print("Machine learning provides {} the ability to learn {}".format("systems", "automatically"))
Machine learning provides systems the ability to learn automatically

我们可以同时对字符串本身和传递给方法的值使用变量。下面的示例代码中,我们定义了一个带占位符的字符串和另外两个变量。我们对该字符串应用 format 方法,并传入这两个变量。该方法读取字符串,并用给定的值替换占位符。

my_string = "{} rely on {} datasets"
method = "Supervised algorithms"
condition = "labeled"
print(my_string.format(method, condition))
Supervised algorithms rely on labeled datasets

重新排序值

在下面的示例中,您在占位符中加入索引号以重新排序值。这会影响方法替换占位符的顺序。

该方法会按照给定顺序用对应的值替换它们。

print("{} has a friend called {} and a sister called {}". format("Betty", "Linda", "Daisy"))
Betty has a friend called Linda and a sister called Daisy

如果我们添加索引号,替换顺序会相应改变。

print("{2} has a friend called {0} and a sister called {1}". format("Betty", "Linda", "Daisy"))
Daisy has a friend called Betty and a sister called Linda

命名占位符

我们也可以引入按关键字名调用的关键字参数。

在下面的示例代码中,我们在占位符中插入了关键字。然后在 format 方法中调用这些关键字,并为每个关键字指定要传递的变量,得到如下输出。

tool="Unsupervised algorithms"
goal="patterns"
print("{title} try to find {aim} in the dataset".format(title=tool, aim=goal))
Unsupervised algorithms try to find patterns in the dataset

我们来看看下面的代码。我们定义了一个包含键:tool 和 goal 的字典。

my_methods = {"tool": "Unsupervised algorithms", "goal": "patterns"}

我们希望将它们的值插入到字符串中。在占位符内部,我们可以使用方括号表示法,指定变量 data 的键 tool 所关联的值。data 是在方法中指定的字典,tool 是该字典中存在的键。

print('{data[tool]} try to find {data[goal]} in the dataset'.format(data=my_methods))

这样就得到了如下所示的期望输出。注意!需要在不使用引号的情况下指定索引。

Unsupervised algorithms try to find patterns in the dataset

格式说明符

我们还可以在花括号内指定格式说明符。这定义了各个值的呈现方式。这里我们将使用“索引:说明符”的语法。最常见的格式说明符之一是用 f 表示的浮点数。在代码中,我们指定索引 0 处传入的值将以浮点数显示。

print("Only {0:f}% of the {1} produced worldwide is {2}!". format(0.5155675, "data", "analyzed"))
Only 0.515567% of the data produced worldwide is analyzed!

我们还可以添加 .2f,表示希望该浮点数保留两位小数,如结果输出所示。

print("Only {0:.2f}% of the {1} produced worldwide is {2}!".format(0.5155675, "data", "analyzed"))
Only 0.52% of the data produced worldwide is analyzed!

格式化 datetime

Python 有一个名为 datetime 的模块,例如,它可以获取今天的日期和时间。

from datetime import datetime
print(datetime.now())
2020-08-08 06:28:42.715243

但由于返回的格式较为特殊,您可以使用诸如 %y-%m-%d-%h-%m 的格式说明符,将其调整为我们更熟悉的格式!

print("Today's date is {:%Y-%m-%d %H:%M}".format(datetime.now()))
Today's date is 2020-08-08 06:29

交互式示例

在以下示例中,您将把 wikipedia_article 的第 4 到第 19 个字符,以及第 22 到第 44 个字符的子串,分别赋值给变量 first_pos 和 second_pos。将字符串调整为小写。最后,打印变量 first_pos 和 second_pos。

# Assign the substrings to the variables
first_pos = wikipedia_article[3:19].lower()
second_pos = wikipedia_article[21:44].lower()

当我们运行上述代码时,会产生如下结果:

computer science artificial intelligence

亲自试一试。

要进一步了解位置格式化,请观看我们课程 Regular Expressions in Python 中的这个视频。

本文内容选自 Maria Eugenia Inzaugarat 在 DataCamp 推出的课程 Regular Expressions in Python。

查看我们的 Python 字符串教程。

主题