如何在python中对齐文本输出

如何在python中对齐文本输出

本文介绍了如何在python中对齐文本输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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

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

>>>下 = [70, 79, 88, 97, 106, 115]>>>上 = [78, 87, 96, 105, 114, 123]>>>数量 = [5, 3, 4, 2, 6, 4]>>>数字 = len(str(max(lower + upper)))>>>数字3>>>f = '{0:>%d}-{1:>%d}: {2}' %(数字,数字)>>>F'{0:>3}-{1:>3}: {2}'>>>对于我在范围内(len(num)):打印(f.格式(下[i],上[i],'*' * num[i]))70-78:****79-87:***88-96:****97-105:**106-114:*****115-123:****

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

>>>对于我在范围内(len(num)):print('{0:>{numLength}}-{1:>{numLength}}: {2}'.format(lower[i], upper[i], '*' * num[i], numLength=数字))

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. You can do that using {0:>5}; this would align parameter 0 to 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:

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

这篇关于如何在python中对齐文本输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 06:15