String formatting: Columns in line
Solution 1:
str.format()
is making your fields left aligned within the available space. Use alignment specifiers to change the alignment:
'<'
Forces the field to be left-aligned within the available space (this is the default for most objects).
'>'
Forces the field to be right-aligned within the available space (this is the default for numbers).
'='
Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form ‘+000000120’. This alignment option is only valid for numeric types.
'^'
Forces the field to be centered within the available space.
Here's an example (with both left and right alignments):
>>> for args in (('apple', '$1.09', '80'), ('truffle', '$58.01', '2')):
... print '{0:<10} {1:>8} {2:>8}'.format(*args)
...
apple $1.09 80
truffle $58.01 2
Solution 2:
With python3 f-strings (not your example but mine):
alist = ["psi", "phi", "omg", "chi1", "chi2", "chi3", "chi4", "chi5", "tau"]
for ar in alist:
print(f"{ar: >8}", end=" ")
print()
for ar in alist:
ang = ric.get_angle(ar)
print(f"{ang:8.4}", end=" ")
print()
generates
psi phi omg chi1 chi2 chi3 chi4 chi5 tau
4.574 -85.28 178.1 -62.86 -65.01 -177.0 80.83 8.611 115.3
Solution 3:
I think the better way is auto adjust the column width from its content
rows = [('apple', '$1.09', '80'), ('truffle', '$58.01', '2')]
lens = []
for col in zip(*rows):
lens.append(max([len(v) for v in col]))
format = " ".join(["{:<" + str(l) + "}" for l in lens])
for row in rows:
print(format.format(*row))
Output:
apple $1.09 80
truffle $58.01 2
Demo: https://code.sololearn.com/cttJgVTx55bm/#py