您最初的问题是如何避免在格式字符串中的字段之间放置任意空格。你是对的,试图避免这种情况。更灵活的是不对列的填充宽度进行硬编码。
您可以使用格式字符串外部定义的WIDTH“常量”来执行这两项操作。然后宽度作为参数传递给format函数,并插入到替换字段内的另一组括号中的格式字符串中:{foo:>{width}}:
如果要更改列宽,只需更改“常量”WIDTH:
human_score = [1.23, 2.32,3.43,4.24]
machine_score = [0.23, 4.22,3.33,5.21]
WIDTH = 12
mean = "Mean:"
std = "Std:"
print '{0:>{width}}{1:>{width}}'.format('line 1', 'line 2', width=WIDTH)
for h, m in zip(human_score, machine_score):
print "{:>{width}.1f}{:>{width}.3f}".format(h,m, width=WIDTH)
print "{mean}{:>{width1}.2f}{:>{width2}.3f}".format(-0.026, 7.26, width1=WIDTH-len(mean), width2=WIDTH, mean=mean)
print "{std}{:>{width1}.2f}{:>{width2}.3f}".format(-2.918, 6.3, width1=WIDTH-len(std), width2=WIDTH, std=std)输出:
line 1 line 2
1.2 0.230
2.3 4.220
3.4 3.330
4.2 5.210
Mean: -0.03 7.260
Std: -2.92 6.300