Reputation: 121
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.
Upvotes: 0
Views: 1955
Reputation: 2303
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 | ]
Upvotes: 0
Reputation: 11134
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 ]
Upvotes: 4
Reputation: 1914
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 ]
Upvotes: 0
Reputation: 473873
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 |
+----+------+---+----+
Upvotes: 3