Reputation: 8119
My table:
2 4,5 100 400
3 20 10 100
4,2 10.000 500 600
9,2 10.024,5 610 1.100
mylist = [['2', '4,5', '100', '400'], ['3', '20', '10', '100'], ['4,2', '10.000', '500', '600'], ['9,2', '10.024,5', '610', '1.100']]
How can I align the numbers like this:
2 4,5 100 400
3 20 10 100
4,2 10.000 500 600
9,2 10.024,5 610 1.100
What I did:
for i in range(0, len(mylist)):
'{:>10} {:>10} {:>10} {:>10}'.format(mylist[i][0], mylist[i][1], mylist[i][2], mylist[i][3])
This gives above results as in the 1st table but the decimals are not aligned.
Update
I adapted the solution of Francisco to the length of the elements in whatever list.
mylist = [['1300', '300', '300'], ['2300,5', '300,5', '300,5'], ['3600000000000', '6000000', '6000000'], ['4200,2345', '200,2345', '200,2345'], ['5301', '301', '301'], ['6200', '200', '200'], ['7300', '300', '300000000'], ['8300,5', '300,500000', '300,5'], ['960000', '600', '6000'], ['10200,2345', '200999,2345', '200,2345'], ['11301', '301', '301'], ['12200', '200', '200'], ['13300', '300', '300'], ['14300,5', '300,5', '300,5']]
column2row = zip(*mylist)
maxbefore = []
maxafter = []
for m in column2row:
maxlengthbefore = 0
maxlengthafter = 0
for e in m:
if ',' in e:
lengthbefore = len(str(e).split(",")[0])
if lengthbefore > maxlengthbefore:
maxlengthbefore = lengthbefore
lengthafter = len(str(e).split(",")[1])
if lengthafter > maxlengthafter:
maxlengthafter = lengthafter
else:
lengthbefore = len(str(e))
if lengthbefore > maxlengthbefore:
maxlengthbefore = lengthbefore
maxbefore.append(maxlengthbefore)
maxafter.append(maxlengthafter + 1)
for m in mylist:
r = 0
for e in m:
if ',' in e:
print(e.rjust(int(maxbefore[r]) + len(e) - e.index(',')).ljust(int(maxbefore[r])+int(maxafter[r])), end=' ')
else:
print(e.rjust(int(maxbefore[r])).ljust(int(maxbefore[r])+int(maxafter[r])), end=' ')
r += 1
print()
Output
1300 300 300
2300,5 300,5 300,5
3600000000000 6000000 6000000
4200,2345 200,2345 200,2345
5301 301 301
6200 200 200
7300 300 300000000
8300,5 300,500000 300,5
960000 600 6000
10200,2345 200999,2345 200,2345
11301 301 301
12200 200 200
13300 300 300
14300,5 300,5 300,5
Upvotes: 2
Views: 382
Reputation: 11496
for m in mylist:
for e in m:
if ',' in e:
print(e.rjust(10 + len(e) - e.index(',')).ljust(15), end=' ')
else:
print(e.rjust(10).ljust(15), end=' ')
print()
prints:
2 4,5 100 400
3 20 10 100
4,2 10.000 500 600
9,2 10.024,5 610 1.100
Basically what it does is check if the string has a comma in it.
If it does it checks its place, centers the string to the right checking how many characters there are without counting everything after the comma, and then centers it to the left this time counting the places after the comma.
If there aren't commas in the string it just centers it to the left and to the right.
Upvotes: 1