Python 内置函数

Python format() 函数用于按指定格式格式化值,是 f-string 底层用的函数。

语法

format(value, format_spec)

参数

value:要格式化的值。可选 format_spec:格式规范字符串,如 ".2f"

返回值

返回格式化后的字符串 str

示例

print(format(3.14159, ".2f"))     # 3.14,两位小数
print(format(42, "d"))            # 42
print(format(255, "x"))           # ff,十六进制
print(format(255, "X"))           # FF
print(format(0.5, ".0%"))         # 50%,百分比
print(format(1000000, ","))       # 1,000,000,千位分隔
print(format(42, "05d"))          # 00042,补零到 5 位

输出:

3.14
42
ff
FF
50%
1,000,000
00042

注意事项

format 的格式规范和 f-string 的冒号后一致:f"{x:.2f}" 等价于 format(x, ".2f")