打印输出整数
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