Python编程:格式化输出、常量与海龟绘图
1. 格式化输出数字
在Python中,我们可以使用f-string来格式化输出数字。以下是一个示例代码,展示了如何将数字以两列的形式输出,并且每个数字占据10个字符的宽度,同时保留两位小数:
# This program displays the following numbers
# in two columns.
num1 = 127.899
num2 = 3465.148
num3 = 3.776
num4 = 264.821
num5 = 88.081
num6 = 799.999
# Each number is displayed in a field of 10 spaces
# and rounded to 2 decimal places.
print(f'{num1:10.2f}{num2:10.2f}')
print(f'{num3:10.2f}{num4:10.2f}')
print(f'{num5:10.2f}{num6:10.2f}')
程序输出如下:
127.90 3465.15
3.78 264.82
88.08 800.00
2. 值的对齐方式
当一个值显示在比它本身更宽的字段中时,需要将其对齐到字段的右侧、左侧或中间。默认情况下,数字是右对齐的,而字符串是左对齐的。以下是示例代码:
# 数字右对齐
number =
超级会员免费看
订阅专栏 解锁全文
2074

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



