【问题标题】:Prettier output in Python 2.7 [duplicate]Python 2.7 中更漂亮的输出 [重复]
【发布时间】:2013-01-23 21:27:53
【问题描述】:

可能重复:
Python format tabular output

如何将以下代码 (Python 2.7) 的输出放在表格中?

with open('blacklists.bls', 'r') as f:
        L = [dnsbls.strip() for dnsbls in f]
t10 = time.time()
for listofdnsbls in L:
        try:
                t0 = time.time()
                result = socket.gethostbyname("%s.%s" % (ip_reversed(iinput), listofdnsbls))
                t1 = time.time()
                total = t1-t0
                print "%s\t%s\t%s sec" % (listofdnsbls, result, total)
        except (socket.gaierror):
                t2 = time.time()
                error_total = t2-t0
                print "%s\tNo result\t%s sec" % (listofdnsbls, error_total)
t20 = time.time()
totaltotal =t20-t10
print "\nCompleted in: %s sec" % (totaltotal)

目前输出不是很整齐:

rbl.ntvinet.net 77.95.250.11    0.00194096565247 sec
postfix.bondedsender.org    No result   0.329633951187 sec
procmail.bondedsender.org   No result   6.34444999695 sec

我希望它更像这样:

rbl.ntvinet.net             77.95.250.11    0.00194096565247 sec
postfix.bondedsender.org    No result       0.329633951187 sec
procmail.bondedsender.org   No result       6.34444999695 sec

我找到了一些解释如何使用 %1d 和 %2d 的文档,但我无法让它发挥作用,因为它们不是数字而是字符串。

【问题讨论】:

  • %1d 是一个不错的方法,但在应用之前您必须知道每列的最大长度。
  • @ZagorulkinDmitry:不,这不会创建类似表格的输出。

标签: python python-2.7


【解决方案1】:

您也可以在 %s 修饰符中使用数字。数字的符号决定了字符串是左对齐还是右对齐。例如。 %20s 用于右对齐字符串,%-20s 用于左对齐字符串。

【讨论】:

  • 他使用 \t 来获取选项卡列,如果字符串长于选项卡宽度,这将不起作用。另一方面,如果您知道最大长度,则 %99s 将始终有效。如果你不这样做,你可以遍历你的条目并提取最大长度,然后动态构建格式。
  • 这实际上帮助我获得了所需的输出:) 问题是我找到的链接并没有得到很好的解释。猜猜如果我用几个小时来完全理解它,它们会很有意义:)
猜你喜欢
  • 1970-01-01
  • 2016-11-30
  • 2012-04-16
  • 1970-01-01
  • 2014-12-13
  • 2014-08-16
  • 1970-01-01
  • 2013-02-09
  • 1970-01-01
相关资源
最近更新 更多