Sebdarmy
Sebdarmy

Reputation: 145

python print with fixed number of char

I have been searching with pretty print and string/number formatting but couldn't find the right answer yet. I am simply trying to print some message and to have them aligned correctly per column with each having a fixed number of character. If I insert tab, some alignment won't be correct either

the full table is stored in a 2D array.

this is what I have currently

card # White Black Red Blue ap 1.6 ap 2.4 ap 3.2 ap 4.8 width lenght 
1.00000 86.40061 7.94422 63.59993 34.30056 5.56550 6.47734 5.24856 6.96552 14.12500 14.46667 
2.00000 86.20923 7.85607 63.57329 34.36462 4.43349 5.57718 5.03046 7.04776 14.10000 14.46667 
9.00000 86.36097 7.79645 63.60142 34.23694 3.93107 5.43634 4.64917 6.65981 13.77500 14.63333 
10.00000 86.27083 7.80646 63.48926 34.24622 3.49787 4.99527 4.46751 6.73853 14.07500 14.43333 
11.00000 86.19497 7.75656 63.49447 34.09210 3.82019 5.42815 4.60028 6.38847 13.95000 14.60000 

And below is what I would like to get, where each column is made of 10 character. Doesn't matter if it is left or right justified.

card #    White     Black    Red       Blue      ap  1.6  ap 2.4   ap 3.2   ap 4.8   width     lenght 
1.00000   86.40061  7.94422  63.59993  34.30056  5.56550  6.47734  5.24856  6.96552  14.12500  14.46667 
2.00000   86.20923  7.85607  63.57329  34.36462  4.43349  5.57718  5.03046  7.04776  14.10000  14.46667 
9.00000   86.36097  7.79645  63.60142  34.23694  3.93107  5.43634  4.64917  6.65981  13.77500  14.63333 
10.00000  86.27083  7.80646  63.48926  34.24622  3.49787  4.99527  4.46751  6.73853  14.07500  14.43333 
11.00000  86.19497  7.75656  63.49447  34.09210  3.82019  5.42815  4.60028  6.38847  13.95000  14.60000 

Upvotes: 1

Views: 4217

Answers (2)

Sebdarmy
Sebdarmy

Reputation: 145

Thank you @canberk_gurel, this worked perfectly and with the %-10s if i want to change the alignment

for res in range(len(card_result)):
      res_value = ("%.5f" % np.array(card_result[res]))
      print("%10s" % res_value),

Upvotes: 0

directive-41
directive-41

Reputation: 133

As ljust() is deprecated, you should use format.

>>> your_message1 = '86.20923'
>>> your_message2 = '7.85607'
>>> your_message3 = '6.36097'
>>> your_message4 = '34.09210'
>>> print('{:>10}'.format(your_message1) + '{:>10}'.format(your_message2) + '\n'{:>10}'.format(your_message3) + '{:>10}'.format(your_message4))

86.20923   7.85607
 6.36097  34.09210

Of course I expect you'll manage the print more elegantly than my simple example...

Upvotes: 4

Related Questions