如何将 python 中的文本排列到终端中的列中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1356029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I line up text from python into columns in my terminal?
提问by Hobhouse
I'm printing out some values from a script in my terminal window like this:
我从终端窗口中的脚本中打印出一些值,如下所示:
for i in items:
print "Name: %s Price: %d" % (i.name, i.price)
How do I make these line up into columns?
我如何将这些排列成列?
回答by Vinay Sajip
If you know the maximum lengths of data in the two columns, then you can use format qualifiers. For example if the name is at most 20 chars long and the price will fit into 10 chars, you could do
如果您知道两列中数据的最大长度,则可以使用格式限定符。例如,如果名称最多 20 个字符长并且价格适合 10 个字符,您可以这样做
print "Name: %-20s Price: %10d" % (i.name, i.price)
This is better than using tabs as tabs won't line up in some circumstances (e.g. if one name is quite a bit longer than another).
这比使用制表符要好,因为在某些情况下制表符不会对齐(例如,如果一个名称比另一个名称长很多)。
If some names won't fit into usable space, then you can use the .
format qualifier to truncate the data. For example, using "%-20.20s" for the name format will truncate any longer names to fit in the 20-character column.
如果某些名称不适合可用空间,那么您可以使用.
格式限定符来截断数据。例如,使用“%-20.20s”作为名称格式将截断任何更长的名称以适合 20 个字符的列。
回答by John Fouhy
As Vinay said, use string format specifiers.
正如 Vinay 所说,使用字符串格式说明符。
If you don't know the maximum lengths, you can find them by making an extra pass through the list:
如果您不知道最大长度,可以通过额外遍历列表来找到它们:
maxn, maxp = 0, 0
for item in items:
maxn = max(maxn, len(item.name))
maxp = max(maxp, len(str(item.price)))
then use '*'
instead of the number and provide the calculated width as an argument.
然后使用'*'
而不是数字并提供计算出的宽度作为参数。
for item in items:
print "Name: %-*s Price: %*d" % (maxn, item.name, maxp, item.price)
回答by Hobhouse
You can also use the rjust() / ljust() methods for str objects.
您还可以对 str 对象使用 rjust() / ljust() 方法。