Hooseman Hooseman - 29 days ago 6
Python Question

Using .format() in Python to allign a mix of variables and characters

I'm trying to learn how to use Python's .format() to make my console output for a test I'm writing look more readable but I'm not quite wrapping my head around it yet.

My current attempt looks like this:

print('({:d}/{:d}) {} {} {} {}'.format(test, num_tests, *item))


It prints out what I want it to nicely enough but I want to align these different fields so that they always line up no matter how many digits something is. For example, my current output would look something like this:

(9/800) item1 item2 item3 item4
(10/800) item1 item2 item3 item4


Is there a way I can rewrite my format so that it looks like this instead?

(9/800) item1 item2 item3 item4
(10/800) item1 item2 item3 item4

Answer

You may create a custom function and set the str.rjust() for setting the length in which text it to be wrapped. Your custom function can be as:

def my_print(test, num_tests, *item):
    width = 8 
    test = '({:d}/{:d})'.format(test, num_tests).rjust(width)
    items = ''.join(str(i).rjust(width) for i in item)
    print test + items

Sample run:

>>> my_print(9, 800, 'yes', 'no', 'hello')
 (9/800)     yes      no   hello

If it is must to do it via str.format(), you may create custom function to add padding as:

def my_print(test, num_tests, *item):
    test = '{0: >10}'.format('({:d}/{:d})'.format(test, num_tests))
    items = ''.join('{0: >6}'.format(i) for i in item)
    print test + items

Sample run:

>>> my_print(9, 800, 'yes', 'no', 'hello')
   (9/800)   yes    no hello

Check String Format Specification document for the list of all formatting options.

Comments