在Python中,格式化输出是一种常见的操作,用于将数据以特定的格式展示。以下是Python中格式化输出的主要方法:
1. 使用 % 操作符
这是Python早期版本中常用的格式化方法,类似于C语言中的 printf 。
基本语法 : "格式化字符串" % 值
多个值 : "格式化字符串" % (值1, 值2, ...)
常用格式化符号 :
%s :字符串
%d :整数
%f :浮点数
%x :十六进制整数
%o :八进制整数
示例 :
name = "Alice"
age = 25
print("Name: %s, Age: %d" % (name, age))
2. 使用 str.format() 方法
str.format() 是Python 2.6引入的格式化方法,功能更强大且灵活。
基本语法 : "格式化字符串".format(值1, 值2, ...)
位置参数 : "{} {}".format(value1, value2)
关键字参数 : "{name} {age}".format(name="Alice", age=25)
索引 : "{0} {1}".format(value1, value2)
格式化符号 : "{:.2f}".format(3.14159) (保留两位小数)
示例 :
name = "Alice"
age = 25
print("Name: {}, Age: {}".format(name, age))
print("Name: {name}, Age: {age}".format(name=name, age=age))
print("Pi: {:.2f}".format(3.14159))
3. 使用 f string(格式化字符串字面值)
f string 是Python 3.6引入的格式化方法,简洁且高效。
基本语法 : f"格式化字符串"
表达式 : f"{表达式}"
格式化符号 : f"{value:.2f}" (保留两位小数)
示例 :
name = "Alice"
age = 25
print(f"Name: {name}, Age: {age}")
print(f"Pi: {3.14159:.2f}")
4. 使用 string.Template
string.Template 是Python标准库中的模板字符串类,适合简单的字符串替换。
基本语法 : Template("$变量名").substitute(变量名=值)
安全替换 : Template("$变量名").safe_substitute(变量名=值) (避免未定义变量报错)
示例 :
from string import Template
template = Template("Name: $name, Age: $age")
print(template.substitute(name="Alice", age=25))
5. 格式化输出的常见操作
对齐 :
{:>10} :右对齐,宽度10
{:<10} :左对齐,宽度10
{:^10} :居中对齐,宽度10
填充字符 :
{:*>10} :右对齐,宽度10,用 * 填充
数字格式化 :
{:.2f} :保留两位小数
{:,} :千位分隔符
{:b} :二进制格式
{:x} :十六进制格式
示例 :
print(f"{'Alice':>10}") # 右对齐,宽度10
print(f"{3.14159:.2f}") # 保留两位小数
print(f"{1000000:,}") # 千位分隔符
{要么是默认,要么是索引值,要么是关键字 :填充的字符 对齐方式 总长度
print(“{:*^10d}”.format(13))# ****13****
print(“{:*^10.2f}”.format(13))#**13.00***
print(“{:*^10.0f}”.format(2.71828))#****3*****
print(“{:1^10b}”.format(13))#1111101111
print(“{a:*^10d}”.format(a=168))# ***168****
print(“{:*^+10d}”.format(13))#***+13****
print(“{:*^-10d}”.format(13))#***-13****
print(“{:+}”.format(2.756))#+2.756
print("{:.2f}".format(2.756))#2.76能四舍五入
print("{:+10.2%}".format(2.756))
print("{:.2f}".format(2.756))#2.76
print("{:+10.2%}".format(2.756))# +275.60%
print("{:*<+10.2%}".format(2.756))#+275.60%**
print("{:,}".format(135756))#135,756千位分隔样式
:前面没有任何东西,表示用默认的顺序
*表示用*填充,没有的话默认的用空格填充
^表示对齐方式,居中对齐
< 表示左对齐
>右对齐
10表示总长度
d整型,f表示浮点数,b表示二进制,o表示八进制,x十六进制
总结
% 操作符 :适用于简单格式化,但功能有限。
str.format() :功能强大,支持位置和关键字参数。
f string :简洁高效,推荐使用。
string.Template :适合简单的模板替换。
根据需求选择合适的格式化方法。