python格式化应用
九九乘法表:
1 defprintLine(row):2 for col in range(1,row+1):3 print(row*col,end=' ')4 print('')5
6 for row in range(1,10):7 printLine(row)
执行结果:
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
8 16 24 32 40 48 56 64
9 18 27 36 45 54 63 72 81
注意到由于有的数字仅有一位 有的两位 我的乘法表没对齐 好难看!!!
修改:
1 defprintLine(row):2 for col in range(1,row+1):3 print('{0:2}'.format(row*col),end=' ')4 print('')5
6 for row in range(1,10):7 printLine(row)
执行结果:
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
8 16 24 32 40 48 56 64
9 18 27 36 45 54 63 72 81
利用 format()函数进行格式化
取位数“{:2}”、"{:.2f}"等 #分别表示 保留两位数字 /小数点后保留两位数字
- 格式化字符参考文章:
https://www.cnblogs.com/fat39/p/7159881.html
一些细节 :
1. end=' '
- print 打印完成后默认换行(默认参数)
- 关于参数的查找与修改:
- 利用help()函数
help(print)
结果:
Help on built-in function print inmodule builtins:print(...)print(value, ..., sep=' ', end='n', file=sys.stdout, flush=False)
Prints the values to a stream,orto sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
据此修改参数
2.print('') (代码块第四行)
再次利用print的默认参数仅进行换行
3.函数是个好东西 在重复型任务方面
内容来源于网络如有侵权请私信删除
本文介绍如何使用Python编写并格式化九九乘法表,通过调整print函数的参数和利用format()函数来实现输出内容的对齐,使得乘法表更加美观。
3571

被折叠的 条评论
为什么被折叠?



