简体   繁体   English

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

[英]How do I align text output in python?

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]))

str.format already has the possibility to specify alignment. str.format已经可以指定对齐方式。 You can do that using {0:>5} ;您可以使用{0:>5}来做到这一点; this would align parameter 0 to the right for 5 characters.这会将参数0向右对齐 5 个字符。 We can then dynamically build a format string using the maximum number of digits necessary to display all numbers equally:然后,我们可以使用同等显示所有数字所需的最大位数动态构建格式字符串:

>>> 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))

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)
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

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 lower and upper data sets.然后我在我的lower数据集和upper数据集的最后一个点上使用了charNum()函数。 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:所以最终的 tabLength 变量看起来像这样:

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

I then plugged the tabLength variable into the expandTab() function to get proper spacing.然后我将tabLength变量插入expandTab()函数以获得适当的间距。 Here's some example output:这是一些示例输出:

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 ljust and rjust which I'm not all that familiar with right now.如果我这样做了,我可能会研究ljustrjust ,我现在不太熟悉。 I'll leave the question open for a little while in case someone comes up with a better answer.如果有人想出更好的答案,我会暂时搁置这个问题。

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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM