Search code examples
pythonstringformatlong-integertrunk

Trunk long strings in format - Python


I'm printing this table in Python:

          NOMBRE        POBLACIÓN ENFERMOS  SANOS  RATA
       Chile        17000000     0    17000000 0.00 
     Hanslandia      2000000  2000000     0    1.00 
     Bastiland       4000000     0     4000000 -0.01
        Peru        31000000     0    31000000 0.00 
      Bolivia       10000000 10000000     0    1.00 
     Argentina      43000000     0    43000000 0.00 
    Henryboysnia     4200000  4200000     0    1.00 
     Inglaterra     51000000     0    51000000 0.00 
Dondeeldiabloperdioelponcho 500000      0     500000  0.00 
   Laquebradelaji   11000000 11000000     0    1.00 
      Uruguay        2000000     0     2000000 0.00 
      Paraguay       4000000     0     4000000 0.00 
      Suriname       500000      0     500000  0.00 
     Venezuela      31000000 31000000     0    1.00 
   Fantasilandia     3000000     0     3000000 -0.01
        USA         300000000    0    3000000000.00 
       NotUSA       20000000     0    20000000 -0.01
       Mexico       127000000    0    1270000000.00 
     Happyland       5000000     0     5000000 -0.01
UvuvwevweOnyetenyevweUgwembubwemOssas13000000     0    13000000 -0.01

using this format line code:

print("{0: ^20}{1: ^9.0f}{2: ^9.0f}{3: ^9.0f}{4: ^5.2f}".format(mundo[country].name,mundo[country].inhabitants,mundo[country].sick[i],mundo[country].healthy[i],mundo[country].rata[i]))

The thing is, there's this string vuvwevweOnyetenyevweUgwembubwemOssas that's too long and makes the other columns see all disordered. I've researched and, supposedly, if I do {0:. ^20}, the . would trunk the string to 20 characters, but what I get when I get that dot is the first column aligned to the left. Any idea why, and how can I do this?


Solution

  • The number after the caret ^ specifies the total width, which is used for the alignment. The number after the dot . is used to trim the string, see the language spec.

    >>> "{0:^20.20}".format("This-is-much-to-long-to-fit")
    'This-is-much-to-long'
    
    >>> "{0:^20.20}".format("sort")
    '        sort        '
    

    You should also have a look at tabulate.