string的ljust()、rjust()、center()用来对齐
>>> for x in range(1, 11): ... print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ') ... # Note use of 'end' on previous line ... print(repr(x*x*x).rjust(4)) ...1 1 12 4 83 9 274 16 645 25 1256 36 2167 49 3438 64 5129 81 729 10 100 1000>>> for x in range(1, 11): ... print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)) ...1 1 12 4 83 9 274 16 645 25 1256 36 2167 49 3438 64 5129 81 729 10 100 1000
str.zfill()用来给数字型字符串对齐
>>> '12'.zfill(5) '00012' >>> '-3.14'.zfill(7) '-003.14' >>> '3.14159265359'.zfill(5) '3.14159265359'