Python: printing in two columns

I am trying to print a row with two fixed columns. For example, I would like to be able to print:

abc       xyz
abcde     xyz
a         xyz

What is the correct way to format the output line when printing to achieve this? In addition, how is this done before version 2.6 and after version 2.6?

+4
source share
4 answers

You can use the format and specify spaces between columns

'{0:10}  {1}'.format(s1, s2)

Formatting old style

'%-10s' '%s' % (s1,s2)
+10
source

This should work for all element lengths (if they are strings. It is assumed that your data is in two separate lists firstand second.

maxlen = len(max(first, key=len))

for i,j in zip(first, second):
    print "%s\t%s" % (i.ljust(maxlen, " "), j)

Python 2.x, 2.6.

+1

, , . , :

for i in range(len(list1)):
    print("%3i\t%3i" %(list1[i],list2[i]))

This will work in all versions of python. 3i ensures that the output has a field width of 3 characters.

0
source

To -> python3.6

s1='albha'
s2='beta'

f'{s1}{s2:>10}'

#output
'albha      beta'
0
source

Source: https://habr.com/ru/post/1627532/


All Articles