python 格式输出

格式化输出

python格式有两种方法:"%"和format,format功能更强大,可调整格式的顺序,一个变量和格式化多次。

1 使用"%"

1.1 格式符

格式符 描述
%s 字符串 (采用str()的显示)
%r 字符串 (采用repr()的显示)
%c 单个字符及其ASCII码
%u 整数(无符号)
%b 二进制整数
%o 八进制数(无符号)
%d 十进制整数
%i 十进制整数
%x 十六进制数(无符号)
%X 十六进制数大写(无符号)
%e 指数 (基底写为e),用科学计数法格式化浮点数
%E 指数 (基底写为E),作用同%e
%f 浮点数,可指定小数点后的精度
%g %f和%e的简写,指数(e)或浮点数 (根据显示长度)
%G %F和%E的简写,指数(E)或浮点数 (根据显示长度)
%p 用十六进制数格式化变量的地址
%% 转义,字符"%"
%10.2s 截取2字符,显示成10个字符,多出的补空格
%10.2f 小数点2个字符,加小数点显示成10个字符,多出的补空格
%010.2f 小数点2个字符,加小数点显示成10个字符,多出的补0
%+010.2f 小数点2个字符,加小数点显示成10个字符,多出的补0,且添加符号位

1.2 字符串输出(%s)

%10s——右对齐,占位符10位
%-10s——左对齐,占位符10位
%.2s——截取2位字符串
%10.2s——10位占位符,截取两位字符串

# 字符串输出
print('%s' % 'hello world')    # 结果:hello world
# 右对齐,取20位,不够则补位
print('%20s' % 'hello world')    # 结果:         hello world
# 左对齐,取20位,不够则补位
print('%-20s' % 'hello world')    # 结果:hello world         
# 取2位
print('%.2s' % 'hello world')    # 结果:he
# 右对齐,占位符10位,取2位
print('%10.2s' % 'hello world')    # 结果:        he
# 左对齐,占位符10位,取2位
print('%-10.2s' % 'hello world')    # 结果:he        

1.3 浮点数输出(%f)

  • %f ——保留小数点后面六位有效数字
    %.3f,保留3位小数位
    %5.1f,保留1位小数位,整个数值少于5个数(包括小数点),左侧添加空格,比如12.3,会显示为 12.3
    %05.1f,保留1位小数位,整个数值少于5个数(包括小数点),左侧添加0,比如12.3,会显示为012.3
    %+05.1f,保留1位小数位,整个数值少于5个数(包括小数点),左侧添加0,并添加符号位比如-12.3,会显示为-012.3
  • %e ——保留小数点后面六位有效数字,指数形式输出
    %.3e,保留3位小数位,使用科学计数法
  • %g ——在保证六位有效数字的前提下,使用小数方式,否则使用科学计数法
    %.3g,保留3位有效数字,使用小数或科学计数法
# 默认保留6位小数
print('%f' % 1.11)    # 1.110000
#  取1位小数
print('%.1f' % 1.11)    # 结果:1.1
# 默认6位小数,用科学计数法
print('%e' % 1.11)    # 结果:1.110000e+00
# 取3位小数,用科学计数法
print('%.3e' % 1.11)    # 结果:1.110e+00
# 默认6位有效数字
print('%g' % 1111.1111)    # 结果:1111.11
# 取7位有效数字
print('%.7g' % 1111.1111)    # 结果:1111.111
# 取2位有效数字,自动转换为科学计数法
print('%.2g' % 1111.1111)    # 结果:1.1e+03

1.4 %s与%r

  • %r表示的用repr()处理;
  • %s表示用str()处理一样。
    两者的区别组要在格式字符串的时候,%r会在字符串两侧带上单引号''或者双引号""(优先带单引号'',如果字符串中有单引号则带双引号),格式数字的时候,%s和%r结果一样。
print('%s' % 123)     # 123
print('%r' % 123)     # 123
print('%s' % '123')   # 123
print('%r' % '123')   # '123'
print('%r' % "don't") # "don't"

2 使用format

2.1 位置匹配

  1. 不带参数,即{}
  2. 带数字参数,可调换顺序,即{1}、
  3. 带关键字,即{a}、
# 不带参数
print('{} {}'.format('hello','world'))    # 结果:hello world
# 带数字参数
print('{0} {1}'.format('hello','world'))    # 结果:hello world
# 参数顺序倒乱
print('{0} {1} {0}'.format('hello','world'))    # 结果:hello world hello
# 带关键字参数
print('{a} {tom} {a}'.format(tom='hello',a='world'))    # 结果:world hello world

# 通过索引
coord = (3, 5)
print('X: {0[0]};  Y: {0[1]}'.format(coord))    # 结果:'X: 3;  Y: 5'
# 通过key键参数
a = {'a': 'test_a', 'b': 'test_b'}
print('X: {0[a]};  Y: {0[b]}'.format(a))    # 结果:'X: test_a;  Y: test_b'

2.2 格式转换

{[index][:type]}或者{[index][!type]},推荐使用[index][!type],因为type=r的时候不能使用前面的方式

print('{:r}'.format('123'))  # 会报错
print('{0:r}'.format('123')) # 会报错
print('{!r}'.format('123'))  # 输出'123'
print('{0!r}'.format('123')) # 输出'123'
符号 描述
'b' 二进制。将数字以2为基数进行输出
'c' 字符。在打印之前将整数转换成对应的Unicode字符串
'd' 十进制整数。将数字以10为基数进行输出
'o' 八进制。将数字以8为基数进行输出
'x' 十六进制。将数字以16为基数进行输出,9以上的位数用小写字母
'e' 幂符号。用科学计数法打印数字。用'e'表示幂
'g' 一般格式。将数值以fixed-point格式输出。当数值特别大的时候,用幂形式打印
'n' 数字。当值为整数时和'd'相同,值为浮点数时和'g'相同。不同的是它会根据区域设置插入数字分隔符
'%' 百分数。将数值乘以100然后以fixed-point('f')格式打印,值后面会有一个百分号
's' 等效于%s
'r' 等效于%r
print('{0:b}'.format(3))    # 结果:11
print('{:c}'.format(20))    # 结果:�
print('{:d}'.format(20))    # 结果:20
print('{:o}'.format(20))    # 结果:24
print('{:x}'.format(20))    # 结果:14
print('{:e}'.format(20))    # 结果:2.000000e+01
print('{:g}'.format(20.1))    # 结果:20.1
print('{:f}'.format(20))    # 结果:20.000000
print('{:n}'.format(20))    # 结果:20
print('{:%}'.format(20))    # 结果:2000.000000%

2.3 高阶用法

  • 进制转换
print("int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42))
# 输出:int: 42;  hex: 2a;  oct: 52;  bin: 101010
 
print("int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42))
# 在前面加“#”,则带进制前缀
# 输出:int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010
  • 对齐
符号 描述
< 左对齐(默认)
> 右对齐
^ 居中对齐
= 在小数点后进行补齐(只用于数字)
  • 取位数 “{:4s}”、"{:.2f}"等
# 默认左对齐
print('{} and {}'.format('hello','world'))    # 结果:hello and world
# 取10位左对齐,取10位右对齐
print('{:10s} and {:>10s}'.format('hello','world'))   # 结果:hello      and      world
# 取10位中间对齐
print('{:^10s} and {:^10s}'.format('hello','world'))    # 结果:  hello    and   world   
 
# 取2位小数
print('{} is {:.2f}'.format(1.123,1.123))    # 结果:1.123 is 1.12
# 取2位小数,右对齐,取10位
print('{0} is {0:>10.2f}'.format(1.123))    # 结果:1.123 is       1.12
 
# 左对齐
print('{:<30}'.format('left aligned'))     # 结果:'left aligned                  '
# 右对齐
print('{:>30}'.format('right aligned'))    # 结果:'                 right aligned'
# 中间对齐
print('{:^30}'.format('centered'))    # 结果:'           centered           '
# 使用“*”填充
print('{:*^30}'.format('centered'))    # 结果:'***********centered***********'
# 还有“=”只能应用于数字,这种方法可用“>”代替
print('{:0=30}'.format(11))    # '000000000000000000000000000011'
  • 正负符号显示正负符号显示 %+f, %-f, 和 % f的用法
# 总是显示符号
print('{:+f}; {:+f}'.format(3.14, -3.14))    # '+3.140000; -3.140000'
# 若是+数,则在前面留空格
print('{: f}; {: f}'.format(3.14, -3.14))    # ' 3.140000; -3.140000'
# -数时显示-,与'{:f}; {:f}'一致
print('{:-f}; {:-f}'.format(3.14, -3.14))    # '3.140000; -3.140000'
  • 百分数%
points = 19
total = 22
print('Correct answers: {:.2%}'.format(points/total))    # 'Correct answers: 86.36%'
  • 逗号作为千位分隔符,金额表示
print('{:,}'.format(1234567890))    # '1,234,567,890'
  • format变形用法

在字符串前加f以达到格式化的目的,在{}里加入对象,此为format的另一种形式

name = 'jack'
age = 18
sex = 'man'
job = "IT"
salary = 9999.99
 
print(f'my name is {name.capitalize()}.')    # my name is Jack.
print(f'I am {age:*^10} years old.')    # I am ****18**** years old.
print(f'I am a {sex}')    # I am a man
print(f'My salary is {salary:10.3f}')    # My salary is   9999.990
posted @ 2023-09-08 17:11  下夕阳  阅读(98)  评论(0编辑  收藏  举报