Printing string with two columns
31,443
Solution 1
You can use format and mention fix spaces between columns
'{0:10} {1}'.format(s1, s2)
Old Style formatting
'%-10s' '%s' % (s1,s2)
Solution 2
This should work for all lengths of the elements (assuming they are strings. This assumes your data is in two seperate lists first
and second
.
maxlen = len(max(first, key=len))
for i,j in zip(first, second):
print "%s\t%s" % (i.ljust(maxlen, " "), j)
This works in Python 2.x, before and after 2.6.
Solution 3
Prior to >=python3.6
s1='albha'
s2='beta'
f'{s1}{s2:>10}'
#output
'albha beta'
Author by
Victor Brunell
Updated on September 23, 2021Comments
-
Victor Brunell over 2 years
I'm trying to print a string with two fixed columns. For example, I'd like to be able to print:
abc xyz abcde xyz a xyz
What is the correct way to format the output string when printing to achieve this? Also, how is this done before version 2.6 and after version 2.6?