在python中用ljust列化

2024-09-30 12:29:12 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我用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)

输出如下:

^{pr2}$

如何使用ljust()在一个漂亮的列中获得输出?在


Tags: 脚本urldatasiteopenurlscountryprint
1条回答
网友
1楼 · 发布于 2024-09-30 12:29:12

这个怎么样-没有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)

一。在

^{pr2}$

编辑:

如果您不知道需要在格式化字符串中使用*多长的列。
但是在找到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    |

相关问题 更多 >

    热门问题