Python从di在线打印

2024-09-30 20:32:26 发布

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

我是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]))

我的字典里有一本词典。 问题是有些名字比其他名字长得多,所以标签不对齐。 以及我的标题:“名称”|“价格”应该与下面的信息一致。 我已经找到了一些解决办法,但我不太明白我找到的那些。 预期结果:

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

Tags: name程序密码字典with方案价格名字
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

试试这个:

这是你的字典

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]))

相关问题 更多 >