Yannis Yannis - 20 days ago 13
Python Question

Pretty print using string format for a namedtuple list with padding (Python)

I have a list

lst
of
entries = namedtuple( 'Entry', ['title', 'x', 'y', 'val'])
where each element
elm
of the
lst
is of
<class 'generator'>
.

I have a method which prints the elements of that list like so:

def print_elements_lst(lst_to_print):
return "\n".join("%s %s %s %s" % elm for elm in lst_to_print)


My issue is that I am trying to add padding between the 1st and 2nd strings (i.e. between the
'title'
and
'x'
) so that there will be a consistent number of empty spaces between them.

From here, I compute the desired padding like so:

pad = max(len(token) for elm in lst_to_print) + 2


But I am having problems on how to implement this in the formatted output along with the
namedtuple
values.

Any suggestions?

Answer

Make the formatting string change depending on the pad value.

>>> pad = 20
>>> fmt = "%-{}s %s %s %s".format(pad)
>>> fmt  # `-20s`: left align (width = 20), without `-` -> right align
'%-20s %s %s %s'
>>> fmt % ('hello', 1, 2, 3)
'hello                1 2 3'

>>> def print_elements_lst(lst_to_print):
...     pad = max(len(elm.title) for elm in lst_to_print) + 2
...     fmt = "%-{}s %s %s %s".format(pad)  # Specify width depending on `pad`
...     return "\n".join(fmt % elm for elm in lst_to_print)
...
>>> Entry = namedtuple( 'Entry', ['title', 'x', 'y', 'val'])
>>> entries = [
...     Entry('Hello world', 1, 2, 10),
...     Entry('Python', 20, 2, 10),
... ]
>>> print(print_elements_lst(entries))
Hello world   1 2 10
Python        20 2 10