I have a list of strings of variable lengths, and I want to pretty-print them so they are lining up in columns. I have the following code, which works as I want it to currently, but I feel it is a bit ugly. How can I simplify it/make it more pythonic (without changing the output behaviour)?
For starters I think I could probably use the alignment
'<' option of the
str.format stuff if I could just figure out the syntax properly...
def tabulate(words, termwidth=79, pad=3): width = len(max(words, key=len)) ncols = max(1, termwidth // (width + pad)) nrows = len(words) // ncols + (1 if len(words) % ncols else 0) #import itertools #table = list(itertools.izip_longest(*[iter(words)]*ncols, fillvalue='')) # row-major table = [words[i::nrows] for i in xrange(nrows)] # column-major return '\n'.join(''.join((' '*pad + x.ljust(width) for x in r)) for r in table)