Search code examples
pythonpython-3.xstring-formatting

I want the single digit numbers to line up better with the other multi digit numbers in my table


this is my code

def table():
    print(A)
    print(B)
    print(C)
    print(D)

this is what it looks like

[7, 13, 10, 8]
[12, 14, 6, 5]
[15, 9, 2, 11]
[1, 3, 0, 4]

I want the numbers to line up better, kinda like this.

[ 7, 13, 10,  8]
[12, 14,  6,  5]
[15,  9,  2, 11]
[ 1,  3,  0,  4]

or something better so that it's easier to read it. This would be especially necessary when the table gets bigger.

I found an old post that would solve my problem but I think it's for an older version of python so it doesn't work in the current version of python.

Printing with exactly 1 space if a single digit?


Solution

  • That old question/answer you linked works just fine with the current version of Python, you just need to add parens around the arguments to print (the old print was a statement, not a function, so no parentheses were needed).

    For your specific case, code like:

    print('[{}]'.format(','.join(map('{:3}'.format, A))))
    

    would do the trick. That formats each element (using map) in A to (at least) three spaces wide via '{:3}'.format (you only asked for two, but you happened to leave a space after each comma, and we may as well use it if we encounter three digit values), padding with spaces, joins them together with commas via ','.join, then puts the result in square brackets via '[{}]'.format.