跳至主要内容

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"))