【问题标题】:Python - Printing in line from dictPython - 从dict在线打印
【发布时间】:2019-02-21 19:32:07
【问题描述】:

我是 python 的初学者,我在打印时遇到了困难。 我制作了一个在字典中存储名称和价格的程序。 (例如:{"PERSON_1":"50","PERSON_2":"75","PERSON_WITH_EXTREMELY_LONG_NAME":"80"} 现在的问题是我希望能够以一个不错的方案打印键及其假定值。 我使用了代码:

 for i in eter.eters:
        print(i + "\t | \t" + str(eter.eters[i]))

eter.eters 是我的字典。 问题是某些名称比其他名称长很多,因此选项卡不对齐。 以及我的标题:“名称”| “价格”应与以下信息一致。 我已经查找了一些解决方案,但我不太了解我找到的解决方案。 期望的结果:

**********************************************************************
               De mensen die blijven eten zijn:
**********************************************************************
Naam                            |      bedrag
----------------------------------------------------------------------
PERSON 1                        |      50
PERSON 2                        |      75
PERSON WITH EXTREMELY LONG NAME |      80
**********************************************************************

【问题讨论】:

  • 你能否为你的问题显示所需的输出。
  • 我将它添加到问题中! @skaul05

标签: python printing tabs alignment


【解决方案1】:

试试这个:

假设 eter.eters 是你的字典

print('%-35s | %6s' % ('Names', 'Price')) # align to the left

for k in eter:
    print('%-35s | %6s' % (k,eter[k]))

print("{0:<35}".format('Name')+'|'+"{0:>6}".format('Price'))

for k in eter:
    print("{0:<35}".format(k)+'|'+"{0:>6}".format(eter.eters[k]))

【讨论】:

  • 这效果更好,但现在它的名称居中向右,有没有办法避免这种情况?已经谢谢了!
  • 用另一种方式检查这个网站,有点复杂,但它可以让你做更多的格式化:w3resource.com/python-exercises/string/…
  • @J Kluseczka 感谢您展示如何使用“-”符号!!
【解决方案2】:

您可以尝试获取所有名称并找到它的最大长度。然后使用特殊填充而不是制表符 (\t) 显示每个名称。这段代码应该解释:

>>> d={"Marius":"50","John":"75"}
>>> d
{'Marius': '50', 'John': '75'}
>>> for i in d:
...  print(i)
... 
Marius
John
>>> d = {"Marius":"50","John":"75"}
>>> m = 0
>>> for i in d:
...  m = max(m, len(i))
... 
>>> m
6 # now we know the place reserved for Name column should be 6 chars width
>>> for i in d:
...  print( i + (m-len(i))*' ' , d[i]) # so add to the name space char that fit this 6 chars space
... 
Marius 50
John   75

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    • 2018-03-26
    • 1970-01-01
    • 2017-03-14
    • 2020-07-19
    • 1970-01-01
    • 2017-01-10
    相关资源
    最近更新 更多