def columnify(iterable):
# First convert everything to its repr
strings = [repr(x) for x in iterable]
# Now pad all the strings to match the widest
widest = max(len(x) for x in strings)
padded = [x.ljust(widest) for x in strings]
return padded
Now you should be able to use pprint.pprint(compact=True)
, or textwrap
, or other tools to get the formatting however you want.
But if you want to do it manually, it's not too hard to do anything you want. For example:
def colprint(iterable, width=72):
columns = columnify(iterable)
colwidth = len(columns[0])+2
perline = (width-4) // colwidth
print('[ ', end='')
for i, column in enumerate(columns):
print(column, end=', ')
if i % perline == perline-1:
print('\n ', end='')
print(' ]')
So:
>>> arr = ['a', 'b', 'cdefg', 'jk', 'lmnopqr', 'st', 'uv', 'wxyz', 1, 2, 3, 4]
>>> colprint(arr, 60)
[ 'a' , 'b' , 'cdefg' , 'jk' , 'lmnopqr',
'st' , 'uv' , 'wxyz' , 1 , 2 ,
3 , 4 , ]
This still won't give you exactly what ls
does; for example, ls
has some heuristics that try to make sure that filenames that are "too long" don't count toward the max width, and instead span multiple columns. If you really want to do everything exactly the same as ls
, you probably need to look at the source code and translate from C to Python…
Also, take a look at pprint
. Whenever a module's documentation starts off with a link to the source code, that means the module was meant to serve as useful sample code, as well as to be useful on its own. So, if you want to look at the rules it uses to determine when to split lines (based on the compact
flag as well as the widths), you should be able to figure it out from there.