Search code examples
pythonformattingpretty-print

Horizonatal alignment with python print / write functions?


Often I need print lists, dictionaries etc. with nice horizontal alignment (something like tab in MS-Word but not \t character).

It is not hard to implement function which does it. E.g.

def printDictTabed(dct,ntab=10):
    for k,v in dct.items():
        sk  = str(k)
        tab = ' '*max(0,ntab-len(sk))
        print sk,tab,": ",v

printDictTabed({454:99897754545,"x":5454,"john":"whatever"},ntab=6)

Output:

x       :  5454
john    :  whatever
454     :  99897754545

But isn't this possible to do somehow using standard python formating?


Solution

  • Padding and aligning strings

    By default values are formatted to take up only as many characters as needed to represent the content. It is however also possible to define that a value should be padded to a specific length.

    Unfortunately the default alignment differs between old and new style formatting. The old style defaults to right aligned while for new style it's left.

    https://pyformat.info/

    Align right:

    Old

    '%10s' % ('test',)
    

    New

    '{:>10}'.format('test')
    

    Align left:

    Old

    '%-10s' % ('test',)
    

    New

    '{:10}'.format('test')
    

    your example:

    def printDictTabed(dct):
        for k,v in dct.items():
            print('{:10}:{:>15}'.format(str(k), str(v)))
    
    printDictTabed({454:99897754545,"x":5454,"john":"whatever"})
    

    output:

    454       :    99897754545
    x         :           5454
    john      :       whatever