0

Let's say I have an array of numbers where

list = [(4, 3, 7, 23),(17, 4021, 4, 92)]

and I want to print the numbers out in such a way so that the output looks somewhat like this:

[   4  |   3  |   7  |  23  ] 
[  17  | 4021 |   4  |  92  ]

Where the numbers are as centered as possible and that there is enough space in between the "|" to allow a 4 digit number with two spaces on either side.

How would I do this?

Thank you.

Scout721
  • 91
  • 1
  • 3
  • 8

4 Answers4

4

str.center can make things easier.

for i in list:
    print '[ ' + ' | '.join([str(j).center(4) for j in i]) + ' ]'

Output:

[  4   |  3   |  7   |  23  ]
[  17  | 4021 |  4   |  92  ]

In case you need an alternative solution, you can use str.format:

for i in list:
    print '[ ' + ' | '.join(["{:^4}".format(j) for j in i]) + ' ]'

Output:

[  4   |  3   |  7   |  23  ]
[  17  | 4021 |  4   |  92  ]
Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
  • Instead of hard coding _4,_ you may want to do: `_list = [(4, 3, 7, 23),(17, 4021, 4, 92)] ; lst = [len(str(x)) for i in _list for x in i] ; _width = max(lst) ;` – boardrider Aug 25 '16 at 18:09
3

You can also use third-parties like PrettyTable or texttable. Example using texttable:

import texttable

l = [(4, 3, 7, 23),(17, 4021, 4, 92)]

table = texttable.Texttable()
# table.set_chars(["", "|", "", ""])
table.add_rows(l)

print(table.draw())

Would produce:

+----+------+---+----+
| 4  |  3   | 7 | 23 |
+====+======+===+====+
| 17 | 4021 | 4 | 92 |
+----+------+---+----+
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
0

Here:

list = [[4, 3, 7, 23],[17, 4021, 4, 92]]

for sublist in list:
    output = "["
    for index, x in enumerate(sublist):
        output +='{:^6}'.format(x) 
        if index != len(sublist)-1:
            output += '|'  
    output +=']'
    print output 

Output:

[  4   |  3   |  7   |  23  ]
[  17  | 4021 |  4   |  92  ]
dheiberg
  • 1,914
  • 14
  • 18
0

This works - for details refer to Correct way to format integers with fixed length and space padding and Python add leading zeroes using str.format

list = [(4, 3, 7, 23),(17, 4021, 4, 92)]
for sublist in list:
    print('[ ', end =" ")
    for val in sublist:
        print("{:4d}".format(val) + ' | ' , end =" ")
    print('] ')

Sample output

[     4 |     3 |     7 |    23 |  ] 
[    17 |  4021 |     4 |    92 |  ] 
LeslieM
  • 2,105
  • 1
  • 17
  • 8