9

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?

Victor Brunell
  • 3,780
  • 8
  • 26
  • 39

4 Answers4

16

You can use format and mention fix spaces between columns

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

Old Style formatting

'%-10s' '%s' % (s1,s2)
AlokThakur
  • 3,073
  • 1
  • 15
  • 30
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.

L3viathan
  • 23,792
  • 2
  • 46
  • 64
1

Prior to >=python3.6

s1='albha'
s2='beta'

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

#output
'albha      beta'
Roushan
  • 3,046
  • 3
  • 15
  • 31
0

There are a number of ways of doing this and it depends on how the data is stored. Assumining your data is stored in equal length lists:

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

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

BenJ
  • 436
  • 2
  • 6
  • 1
    Wouldn't that produce a misaligned output? The second column wouldn't be in a fixed position if the first `%d` changes length. It would just be one tab off from the last character. – Victor Brunell Feb 06 '16 at 02:53
  • You are right I have corrected the answer to show padding to 3 characters – BenJ Feb 06 '16 at 02:55
  • Is there some way to produce the second `%i` 20 spaces from the start of the string? That is, not relative to the first `%i`, but relative to the start of the string itself? – Victor Brunell Feb 06 '16 at 02:58
  • I think you want the .format method https://docs.python.org/2/library/string.html for use on strings. – BenJ Feb 06 '16 at 03:03
  • Yeah, I was just hoping to find some method for doing this before version 2.6. I'm working on a server that only supports version 2.4. – Victor Brunell Feb 06 '16 at 03:05
  • Ahh thr python documentation doesnt go back that far to 2.4. But you could use str.ljust http://stackoverflow.com/questions/5676646/fill-out-a-python-string-with-spaces and on each iteration calculate the length of the left hand field and pad the second column the right length for consistency – BenJ Feb 06 '16 at 03:14