0
Dic = {"War and Peace":60,"Les Miserables":88,"A Tale of Two Cities":75,\
"Jane Eyre":23,"Wuthering Heights":56}

这就是我所做的,对齐是如此混乱

print("Title","Pages",sep="\t\t\t")
for l,v in Dic.items():
    print(l,v,sep="\t\t\t")
4

3 回答 3

5

您可以使用format方法来格式化这样的字符串

myDict = {"War and Peace":60,"Les Miserables":88,"A Tale of Two Cities":75,\
"Jane Eyre":23,"Wuthering Heights":56}
for l, v in myDict.items():
    print "{:20} {:10}".format(l, v)

输出

Jane Eyre                    23
Wuthering Heights            56
War and Peace                60
Les Miserables               88
A Tale of Two Cities         75
于 2013-11-09T05:30:02.823 回答
0

使用带字段宽度的 string.format() 很好。这为您提供了在宽字段中填充的字符串,即用空格填充。

有时我喜欢使用单个表来分隔我的 python 代码中的列,并将结果通过管道传递到 *ix “expand” 命令中。Expand 允许您将制表符转换为任意数量的空格。这样,演示文稿就不会被编码到您的 Python 程序中。

例如:

$ python3 -c 'print(1, "\t", 2)' | expand -30
1                              2
于 2013-11-09T06:22:12.313 回答
0
>>> d = {"War and Peace":60,"Les Miserables":88,"A Tale of Two Cities":75,\
... "Jane Eyre":23,"Wuthering Heights":56}

>>> print ["%20s%4s"%(k, d[k]) for k in d]
['           Jane Eyre  23', 
 '   Wuthering Heights  56', 
 '       War and Peace  60', 
 '      Les Miserables  88', 
 'A Tale of Two Cities  75']

如果您想指定为left alignment使用

>>> print [("%-20s%-4s"%(k, d[k])).strip() for k in d]
['Jane Eyre           23', 
 'Wuthering Heights   56', 
 'War and Peace       60', 
 'Les Miserables      88',
 'A Tale of Two Cities75']
于 2013-11-09T06:33:53.043 回答