如何在python中对齐文本输出?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17091446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:24:45  来源:igfitidea点击:

How do I align text output in python?

pythonpython-3.x

提问by CopOnTheRun

So I've got a function which creates a little star table based on some data collected elsewhere in the program. While the table produces the correct output, since the number of characters in each number changes, it un-aligns the table. For example,

所以我有一个函数,它根据程序中其他地方收集的一些数据创建一个小星表。虽然表格产生了正确的输出,但由于每个数字中的字符数会发生变化,因此表格会取消对齐。例如,

70-78: *****
79-87: ***
88-96: ****
97-105: **
106-114: ******
115-123: ****

Is there any way to make the stars align (hehe) so that the output is something like this:

有没有办法让星星对齐(呵呵),这样输出是这样的:

70-78:   *****
79-87:   ***
88-96:   ****
97-105:  **
106-114: ******
115-123: ****

Here's how I currently print the table.

这是我目前打印表格的方式。

for x in range(numClasses):
    print('{0}-{1}: {2}'.format(lower[x],upper[x],"*"*num[x]))

采纳答案by poke

str.formatalready has the possibility to specify alignment. You can do that using {0:>5}; this would align parameter 0to the right for 5 characters. We can then dynamically build a format string using the maximum number of digits necessary to display all numbers equally:

str.format已经可以指定对齐方式。你可以使用{0:>5}; 这会将参数0向右对齐5 个字符。然后,我们可以使用同等显示所有数字所需的最大位数动态构建格式字符串:

>>> lower = [70, 79, 88, 97, 106, 115]
>>> upper = [78, 87, 96, 105, 114, 123]
>>> num = [5, 3, 4, 2, 6, 4]
>>> digits = len(str(max(lower + upper)))
>>> digits
3
>>> f = '{0:>%d}-{1:>%d}: {2}' % (digits, digits)
>>> f
'{0:>3}-{1:>3}: {2}'
>>> for i in range(len(num)):
        print(f.format(lower[i], upper[i], '*' * num[i]))

 70- 78: *****
 79- 87: ***
 88- 96: ****
 97-105: **
106-114: ******
115-123: ****

Actually, you could even use a single format string here with nested fields:

实际上,您甚至可以在此处使用带有嵌套字段的单一格式字符串:

>>> for i in range(len(num)):
        print('{0:>{numLength}}-{1:>{numLength}}: {2}'.format(lower[i], upper[i], '*' * num[i], numLength=digits))

回答by Next Door Engineer

This should do the trick. I assume there are clever ways.

这应该可以解决问题。我认为有一些聪明的方法。

print '70-78:'.ljust(10) + '*****'

You could also use expandtabs()

你也可以使用 expandtabs()

print ('70-78'+'\t'+ '*****').expandtabs(10)

回答by Jacek Przemieniecki

Easy way (in your case) would be to put a tab instead of space:

简单的方法(在您的情况下)是放置一个制表符而不是空格:

for x in range(numClasses):
    print('{0}-{1}:\t{2}'.format(lower[x],upper[x],"*"*num[x]))

Another way would be to use str.ljust:

另一种方法是使用str.ljust

for x in range(numClasses):
    label = '{0}-{1}:'.format(lower[x], upper[x])
    print(label.ljust(10, ' ') + "*" * num[x])

回答by falsetru

lower = [70, 79, 88, 97, 106]
upper = [78, 87, 105, 114, 123]
num = [5, 3, 4, 2, 6, 4]

for l, u, n in zip(lower, upper, num):
    print('{0:<9} {1}'.format('{0}-{1}:'.format(l, u), '*' * n))

http://docs.python.org/3/library/string.html#format-specification-mini-language

http://docs.python.org/3/library/string.html#format-specification-mini-language

回答by CopOnTheRun

Ok, while the solution I'm using is admittedly ad-hoc, it works, and scales better than the answers so far. Basically it's just the method VR17 suggested, but with a little more so that the tab size scales with the data set, and isn't just hard coded in.

好的,虽然我使用的解决方案无可否认是临时的,但它有效,并且比迄今为止的答案更好。基本上它只是 VR17 建议的方法,但还有一点,以便标签大小随数据集缩放,而不仅仅是硬编码。

First I made a method that returns the number characters in some number.

首先,我创建了一个返回某个数字中的数字字符的方法。

def charNum(number):
    return math.floor(math.log(number,10)+1)

Then I used the charNum()function on the last point of my lowerand upperdata sets. Only the last point had to be used on each list because the last point is the biggest number. I then counted the character that weren't numbers(the dash, semicolon, and space), and adjusted accordingly.
So the final tabLength variable looks like this:

然后我用的charNum()上的我的最后一点功能lowerupper数据集。每个列表只需要使用最后一个点,因为最后一个点是最大的数字。然后我计算不是数字的字符(破折号、分号和空格),并相应地进行调整。
所以最终的 tabLength 变量看起来像这样:

tabLength = charNum(lower[-1])+charNum(upper[-1])+3

I then plugged the tabLengthvariable into the expandTab()function to get proper spacing. Here's some example output:

然后我将tabLength变量插入expandTab()函数以获得适当的间距。这是一些示例输出:

1-11:  *******
12-22: *
23-33: ***
34-44: **
45-55: ***
56-66: *

99-249:   *****
250-400:  ****
401-551:  **
552-702:  **
703-853:  *
854-1004: ***

99-200079:      ******
200080-400060:  **
400061-600041:  ****
600042-800022:  **
800023-1000003: *

The only problem I can really see with this is that if I wanted to expand this to a table or something the tabs would be all funky. If I did that though, I'd probably look into ljustand rjustwhich I'm not all that familiar with right now. I'll leave the question open for a little while in case someone comes up with a better answer.

我真正能看到的唯一问题是,如果我想将其扩展到表格或其他内容,选项卡就会很时髦。如果我这样做了,我可能会调查一下ljustrjust而我现在不太熟悉。如果有人想出更好的答案,我会暂时搁置这个问题。