简体   繁体   English

在python中嵌套循环中的漂亮打印输出

[英]Pretty print output in nested loop in python

I have a nested loop like so: 我有一个像这样的嵌套循环:

for a in b.keys():
    for c in b[a]:
        out = '%-30s %s' % (c, a)
        space = out.count(' ')
        split = space * '-'
        print '\t%-30s %s  %-10s' % (c, split, a)

So the result is: 结果是:

test1         ------- something1
test23sdfsf   ----- dsffdgdgfddfsdf

But what I want is: 但我想要的是:

test1 -------------- something1
test23sdfsf -------- dsffdgdgfddfsdf

If you want to use a maxwidth of 30 , do the following: 如果要使用maxwidth 30 ,请执行以下操作:

for a in b.keys():
    for c in b[a]:
        print("%s %s" % (c.ljust(30, '-'), a))

How about using the following: 如何使用以下内容:

Test: {0:15} Something {1}".format(Variable,AnotherVar)

You can calculate the numbers based on the length. 您可以根据长度计算数字。

Adding more example: 添加更多示例:

>>> a="test"
>>> b="another_one"
>>> "A: {0:20} B {1}".format(a,b) 'A: test                 B another_one'
>>> "A: {0:15} B {1}".format(a,b) 'A: test            B another_one'
>>> "A: {0:4} B {1}".format(a,b) 'A: test B another_one'

You can also use a variable for the second number in the first {} based on the length of strings you want to print. 您还可以根据要打印的字符串长度在第一个{}中使用变量作为第二个数字。

You can see the same example for my solution in nested arguments and complex examples 您可以在嵌套参数和复杂示例中看到我的解决方案的相同示例

for a in b.keys():
    for c in b[a]:
        print '{key:{fill}{align}20} {item}'.format(key=key + ' ', fill='-', align='<', item=b[key])

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

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