这是我在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()
答案 0 :(得分: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 |