在Python中使用ljust进行列格式化

0 投票
1 回答
511 浏览
提问于 2025-04-18 10:15

这是我用Python写的脚本的一部分:

print 'Url\t\tpopularity_rank\t\treach_rank\t\tcountry_rank'

urls = open(filename)
for site in urls:
    url = site.rstrip()
    data = Func(url)
    popularity_rank, reach_rank, country_rank = -1, -1, -1
    if data:
        popularity_rank, reach_rank , country_rank = data
        print '%s\t%d\t%d\t%d' % (url, popularity_rank, reach_rank, country_rank)

输出结果大概是这样的:

Url     popularity_rank     reach_rank      country_rank
test.com    228512  222347  -1
test1.com   173834  189659  -1

我该怎么用 ljust() 让输出看起来整齐一些呢?

1 个回答

1

这样怎么样 - 不使用 ljust() 也不使用 \t

values = {
    'test.com': [228512, 222347, -1 ],
    'test1.com': [173834, 189659, -1 ]
}

print '| %-15s | %15s | %15s | %15s |' % ('Url', 'popularity_rank', 'reach_rank', 'country_rank')
print '+' + ('-'*17) + '+' + ('-'*17) + '+' + ('-'*17) + '+' + ('-'*17) + '+'

for url, data in values.items():
    popularity_rank, reach_rank , country_rank = data
    print '| %-15s | %15d | %15d | %15d |' % (url, popularity_rank, reach_rank, country_rank)

.

| Url             | popularity_rank |      reach_rank |    country_rank |
+-----------------+-----------------+-----------------+-----------------+
| test1.com       |          173834 |          189659 |              -1 |
| test.com        |          228512 |          222347 |              -1 |

补充说明:

如果你不知道需要多长的列,可以在格式字符串中使用 *
但你需要在找到 longest 之前知道所有的值。

text = [ 'a', 'abcdef', 'abc' ]

longest = max( len(x) for x in text )

for x in text:
   print "| %*s |" % (longest, x)

print 

for x in text:
   print "| %*s |" % (-longest, x)

.

|      a |
| abcdef |
|    abc |

| a      |
| abcdef |
| abc    |

撰写回答