Trunk长字符串格式 - Python

时间:2017-10-09 19:33:31

标签: python string format long-integer trunk

我用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

使用此格式行代码:

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]))

问题是,这个字符串vuvwevweOnyetenyevweUgwembubwemOssas太长了,而其他列看起来都是无序的。我已经研究过,据说,如果我做{0:. ^20}.会将字符串中继到20个字符,但是当我得到那个点时我得到的是第一个与左边对齐的列。知道为什么,我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

插入符^后面的数字指定用于对齐的总宽度。点.后面的数字用于修剪字符串,请参阅语言spec

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

>>> "{0:^20.20}".format("sort")
'        sort        '

您还应该查看tabulate