格式化输出:% 操作符
Python 2 中最常用的字符串格式化方式是 % 操作符。它借鉴了 C 语言的 printf 风格,用 % 开头的格式符指定如何插入值。虽然 Python 3 更推荐 str.format() 和 f-string,但 % 格式化在 Python 2 代码中无处不在,必须熟练掌握。
基本用法
name = "Alice"
age = 25
print "My name is %s, I am %d years old." % (name, age)
# My name is Alice, I am 25 years old.
% 左边是格式字符串,右边是要插入的值。如果只有一个值,可以省略括号:
print "Pi is %f" % 3.14159
# Pi is 3.141590
常用格式符
| 格式符 | 含义 | 示例 |
|---|---|---|
%s | 字符串(str() 转换) | "%s" % "hello" → "hello" |
%r | 字符串(repr() 转换) | "%r" % "hello" → "'hello'" |
%d | 十进制整数 | "%d" % 42 → "42" |
%i | 同 %d | |
%f | 浮点数 | "%f" % 3.14 → "3.140000" |
%e | 科学计数法 | "%e" % 1234 → "1.234000e+03" |
%x | 十六进制整数 | "%x" % 255 → "ff" |
%X | 大写十六进制 | "%X" % 255 → "FF" |
%o | 八进制整数 | "%o" % 8 → "10" |
%% | 字面量 % | "100%%" → "100%" |
格式控制
在 % 和格式符之间可以插入控制字符:
# 宽度
print "|%10s|" % "hi" # | hi|,右对齐,宽度 10
print "|%-10s|" % "hi" # |hi |,左对齐,宽度 10
# 精度
print "%.2f" % 3.14159 # 3.14,保留 2 位小数
print "%.5s" % "hello" # hello,截取 5 个字符
# 宽度和精度组合
print "%10.2f" % 3.14159 # " 3.14",宽度 10,精度 2
# 前导零
print "%05d" % 42 # 00042,宽度 5,前导零
# 正号
print "%+d" % 42 # +42
print "%+d" % -42 # -42
字典格式化
用 %(key)s 语法,右边传入字典:
data = {"name": "Alice", "age": 25, "city": "Beijing"}
print "%(name)s lives in %(city)s, she is %(age)d years old." % data
# Alice lives in Beijing, she is 25 years old.
这在处理配置、日志模板时非常有用:
template = "Error in %(file)s at line %(line)d: %(message)s"
error = {"file": "main.py", "line": 42, "message": "Index out of range"}
print template % error
类型转换
%s 会调用 str() 转换任何对象:
print "%s" % 42 # "42"
print "%s" % [1, 2, 3] # "[1, 2, 3]"
print "%s" % {"a": 1} # "{'a': 1}"
%r 调用 repr(),返回更精确的对象表示:
print "%r" % "hello" # "'hello'"(带引号)
print "%r" % 42 # "42"
常见错误
类型不匹配:
print "%d" % "42" # TypeError: %d format: a number is required, not str
print "%s" % 42 # 正确,%s 接受任何对象
元数不匹配:
print "%s %s" % "Alice" # TypeError: not enough arguments for format string
print "%s" % ("Alice", "Bob") # TypeError: not all arguments converted
print "%s %s" % ("Alice", "Bob") # 正确
只有一个值时忘记括号:
print "%s" % (1, 2) # 正确,元组 (1, 2) 被当作单个值
print "%s %s" % (1, 2) # 正确,两个值
注意:如果只有一个值且它是元组,必须用 (value,) 或 % (value,):
t = (1, 2)
print "%s" % (t,) # "(1, 2)"
print "%s" % t # TypeError: not enough arguments for format string
# 因为 t 被拆包成两个值 1 和 2
与 str.format() 的选择
Python 2.6+ 支持 str.format(),功能更强大:
# % 格式化
print "%(name)s is %(age)d years old" % {"name": "Alice", "age": 25}
# str.format()
print "{name} is {age} years old".format(name="Alice", age=25)
str.format() 支持更复杂的格式控制(对齐、填充、千位分隔符等),但 % 格式化在 Python 2 中更常见。阅读旧代码时需要熟悉 %,新项目推荐 str.format()。