请帮我格式化同一行的字符串

Please help me with formatting a string on same row

我 运行 遇到格式化连续字符串的问题。

这就是我现在拥有的。

print(line1)
print("%20s"%"",end="")
for i in range(6):
     print("%-12.2f" %avg[i], end="")
print("%-12.2f" %sum(avg))
print(line1)
print("%-10s"%"","%12s"%"Ranks",end="")

当前输出如下所示:

但我需要它看起来像这样:

我不知道如何在后面的数字前加上 AverageTotal

在你的循环中你打印了 avg[i] 值

avg = [1154.20, 1205.50, 1213.10, 1244.90, 1207.10, 1180.70 ]

目前您的代码打印的内容与此类似:

要在该行文本的开头打印“总计”,如屏幕截图所示

您可以尝试在循环外打印文本,实际上就在循环之前,通常这需要换行文本,这是您不想要的,这里有一个简单的方法来避免它 - Python New Line and How to Python Print Without a Newline/freecodecamp.

The new line character in Python is \n. It is used to indicate the end of a line of text. You can print strings without adding a new line with end = , which is the character that will be used to separate the lines.

我将变量 line1avg 添加到您的代码中,以便您可以 运行 并对其进行测试 -如此处所示,我还添加了行 print("Grand Totals", end='');

line1 = "==========================================================================================="
avg = [1154.20, 1205.50, 1213.10, 1244.90, 1207.10, 1180.70 ]
print(line1)
print("Grand Totals", end='');
print("%20s"%"",end="")
for i in range(6):
     print("" + "%-12.2f" %avg[i], end="")
print("%-12.2f" %sum(avg))
print(line1)
print("%-10s"%"","%12s"%"Ranks",end="")

我没有你的其余代码,但我的修改打印出来了

如果您想要文本标签和第一个数值靠得更近一些 - 您可以将此行更改为 10,而不是 20

print("%10s"%"",end="")

结果:

希望对您有所帮助,请随意 post 您的更多代码,我会看看。