Python的格式化输出和format函数总结

打印输出整数

n = 20
print("this is %d" %(n))
>>>this is 20

%s是打印输出字符串
%f是打印浮点数用法与输出整数相同
而且打印浮点数还可以指定位数

n = 20.111
print("this is %.2f" %(n))

>>>this is 20.11

打印指定占位符宽度
都是在字符的前端多出一个空格

print("字符:%9s 整数:%3d 浮点数:%5.2f" % ('KKBBBKKC', 66, 0.88))
>>>字符: KKBBBKKC 整数: 66 浮点数: 0.88

打印指定的占位的字符(左右对齐)
并且将空格的地方用0去填充
左对齐(字符在左,空格在右):

hour1 = 13
m1 = 0
miao1 = 0
print("%-2d:%-2d:%-2d" %(hour1,m1,miao1))
>>>13:0 :0

右对齐

hour1 = 13
m1 = 0
miao1 = 0
print("%2d:%2d:%2d" %(hour1,m1,miao1))
>>>13: 0: 0

将空格处补上0(前导0)

hour1 = 13
m1 = 0
miao1 = 0
print("%02d:%02d:%02d" %(hour1,m1,miao1))
>>>13:00:00

str.format()函数的使用
可以通过位置输出

print('{0},{1},{0}'.format('1111', '222'))
>>>1111,222,1111

通过关键字参数:

print('{a},{b}'.format(a='1111', b='222'))
>>>1111,222

通过下标:

student = ['lihua', 22]
print('{0[0]},{0[1]}'.format(student))
>>>lihua,22

以特定的格式输出(前导0):
这里的0可以替换成自己想设定的其他字符

hour1 = 13
m1 = 0
miao1 = 0
print("{:0>2}:{:0>2}:{:0>2}".format(hour1,m1,miao1))
>>>13:00:00
#浮点数
print('{:.2f}'.format(3.1415926))
>>> 3.14

按进制输出(二进制b,十进制d,八进制o,十六进制x):

print('{:b}'.format(99))
print('{:d}'.format(99))
print('{:o}'.format(99))
print('{:x}'.format(99))
>>>1100011
99
143
63
#实例输出二进制的32个数
for i in range(32):
    print("{:0>5b}".format(i))
>>>00000
00001
00010
00011
00100
00101
00110
00111
01000
01001
01010
01011
01100
01101
01110
01111
10000
10001
10010
10011
10100
10101
10110
10111
11000
11001
11010
11011
11100
11101
11110
11111

此外, 用逗号还能用来做金额的千位分隔符。

print('{:,}'.format(1000000000))
 
>>>1,000,000,000
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值