I am trying to write a function that takes dir(obj) as argument and prints out a perfect list of string tabbed in multiple columns. dir(obj) is a function that generates a list of strings where each string is a method available for the chosen obj. The output, however, is formatted as a single column. I would like to generate tabbed columns instead.
So far I managed to use
lst = dir(str) # naming the variable as lst and trying it out with 'str' object
print(*lst, sep=' \t') # note the amount of white spaces before \t
However, no matter how many times I tried separating them with different quantities of white space (sep=' \t'), the columns always break at some point. Please see below a screen clip from my Jupyter notebook:
I've spend the whole afternoon trying different alternatives, including pprint, columnar and tabulate, but these modules seem to work better with tables. Thus far I have not found a simpler and obvious way to do such a simple and obvious task. what am I missing here, please?
CodePudding user response:
longest = max([len(l) for l in lst])
cols = 5
padding = 5
for i, a in enumerate(lst):
print(a, end=" "*(longest-len(a) padding) if (i 1) % cols else "\n")
will produce a result that looks like this
" "*(longest-len(a) padding) will adjust the columns for the longest variable and add some extra padding.