Python format() 字符串格式化完全指南:占位符、格式化规范、类与字典应用
什么是 Python 字符串 format()?
Python String format() 是用于将占位符替换、替换或转换为有效值的函数。它是 Python 字符串类的内置方法,返回格式化后的字符串。占位符定义在花括号内。
例如:"Welcome to Guru99 {}".format('value here')。
本教程涵盖:
- format() 语法
- format() 工作原理
- 空占位符替换字符串/数值
- 变量/关键字参数占位符
- 索引/位置参数占位符
- 占位符内格式化
- 配合类使用
- 配合字典使用
- 变量替换填充
format() 语法
templatestring.format(val1, val2...)
参数
val1, val2 … : 替换模板字符串中花括号 {} 占位符的值。占位符可以是字符串、键值对、整数、浮点数、字符等。
返回值
返回最终字符串,占位符被有效值替换。
占位符形式
模板字符串中用花括号表示占位符,如 {}。占位符可以是空 {},或包含变量如 {name},或数字索引如 {0}、{1} 等。
format() 工作原理
format() 扫描原字符串寻找占位符。占位符可以是空花括号 {},或位置参数如 {0}、{1}。关键字参数时变量名在花括号内如 {name}、{age}。空花括号按序替换 format() 中的值。位置参数索引从 0 开始。关键字参数时,format() 内值的顺序不重要,按变量名匹配替换。
示例:空占位符替换字符串值
字符串有空花括号 {}。format() 给的值替换进花括号。值为字符串。
print("Welcome to {} tutorials".format("Guru99"))
输出:
Welcome to Guru99 tutorials
示例:空占位符替换数值
需在原字符串插入数值。花括号 {} 加在需数值处。执行时空花括号被数值替换。
print("Welcome to Guru{} Tutorials".format("99"))
输出:
Welcome to Guru99 Tutorials
示例:占位符使用变量/关键字参数
可在花括号内使用变量。变量在 format() 中定义,执行时变量值替换进原字符串。
print("Welcome to {name}{num} Tutorials".format(name="Guru", num="99"))
输出:
Welcome to Guru99 Tutorials
示例:占位符使用索引/位置参数
值可用 0、1、2 等索引在占位符中引用。按 format() 中顺序取值。
print("Welcome to {0}{1} Tutorials".format("Guru","99"))
输出:
Welcome to Guru99 Tutorials
示例:字符串中使用多个空占位符
字符串含多个空占位符,每个对应 format() 中的值,第一个值替换第一个占位符,以此类推。
print("{} is {} new kind of {} experience!".format("Guru99", "totally","learning"))
输出:
Guru99 is totally new kind of learning experience!
占位符内格式化
占位符可以是空、变量、索引,还可在占位符内应用 Python 字符串格式化规范。
| 格式 | 描述 | 示例 |
|---|---|---|
:d | 十进制整数格式 | print("The binary to decimal value is : {:d}".format(0b0011)) → The binary to decimal value is : 3 |
:b | 二进制格式 | print("The binary value is : {:b}".format(500)) → The binary value is : 111110100 |
:e | 科学计数法(小写 e) | print("The scientific value is : {:e}".format(40)) → The scientific format value is : 4.000000e+01 |
:E | 科学计数法(大写 E) | print("The scientific value is : {:E}".format(40)) → The scientific value is : 4.000000E+01 |
:f | 定点数(默认 6 位小数) | print("The value is : {:f}".format(40)) → The value is : 40.000000;{:.2f} 保留 2 位 → 40.00 |
:o | 八进制格式 | print("The value is : {:o}".format(500)) → The value is : 764 |
:x | 十六进制小写 | print("The value is : {:x}".format(500)) → The value is : 1f4 |
:X | 十六进制大写 | print("The value is : {:X}".format(500)) → The value is : 1F4 |
:n | 数字格式(区域感知) | print("The value is : {:n}".format(500.00)) → The value is : 500 |
:% | 百分比格式(默认 6 位小数) | print("The value is : {:%}".format(0.80)) → The value is : 80.000000%;{:.0%} 无小数 → 80% |
:_ | 下划线千分位分隔符(Python 3.6+) | print("The value is {:_}".format(1000000)) → The value is : 1_000_000 |
:, | 逗号千分位分隔符 | print("The value is : {:,}".format(1000000)) → The value is : 1,000,000 |
: | 正数前加空格 | print("The value is: {:5}".format(40)) → The value is: 40 |
:- | 负数前加减号 | print("The value is: {:-}".format(-40)) → The value is: -40 |
:+ | 正数前加加号 | print("The value is: {:+}".format(40)) → The value is: +40 |
:= | 符号靠左对齐 | print("The value is {:=}".format(-40)) → The value is -40 |
:^ | 居中对齐 | print("The value {:^10} is positive value".format(40)) → 居中显示 |
:> | 右对齐 | print("The value {:>10} is positive value".format(40)) → 右对齐 |
:< | 左对齐 | print("The value {:<10} is positive value".format(40)) → 左对齐 |
配合类使用 format()
创建类并在 format() 中使用类对象。占位符引用类属性或方法。
class MyClass:
msg1 = "Guru"
msg2 = "Tutorials"
print("Welcome to {c.msg1}99 {c.msg2}!".format(c=MyClass()))
输出:
Welcome to Guru99 Tutorials!
配合字典使用 format()
也可在 format() 中使用字典:
my_dict = {'msg1': "Welcome", 'msg2': 'Guru99'}
print("{m[msg1]} to {m[msg2]} Tutorials!".format(m=my_dict))
输出:
Welcome to Guru99 Tutorials!
变量替换填充
用 format() 在占位符内添加填充/空格。
print("I have {:5} dogs and {:5} cat".format(2,1))
输出:
I have 2 dogs and 1 cat
也可在占位符用索引如 {0:5}:
print("I have {0:5} dogs and {1:5} cat".format(2,1))
总结
- Python 字符串类提供重要内置
format(),将占位符替换为有效值。 - 占位符用花括号,如
"Welcome to Guru99 {}"。format('value here')。 - 占位符可以是空 {}、变量 {name}、索引 {0}、{1} 等。
- 占位符内可用格式化规范实现填充、居中对齐、数字格式化。
Python
- Python print() 函数完全指南:基础用法、空行打印与自定义结束符
- Python strip() 方法完全指南:去除首尾空白与自定义字符实战
- Python str.count() 完全指南:统计字符与子串出现次数实战
- Python 字符串 find() 方法完全指南:语法、参数、替代方案与计数技巧
- 精通 Python Lambda 函数:实用示例与最佳实践
- Python round() 函数详解与实战示例
- 精通 Python map() 函数:语法、示例与最佳实践
- Python timeit():精准测量代码执行时间与实战示例
- Python collections.Counter:高效计数、更新与算术运算
- 理解 Python type() 与 isinstance():实战示例详解
- 精通 Java String.indexOf():定位子字符串与实战示例
- 精通 Java String compareTo():语法、用例与实战示例