Search code examples
pythonfor-loopmultiple-columnspretty-print

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

Solution

  • If you want to use a maxwidth of 30, do the following:

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