我建议使用format mini-language,设置如下:
bookdict = {
'Little longer title here': 'Author Name Here',
'Book Title Here': 'Another Author Name Here',
'shorter here': 'Diff Name Here'}
bookwidth = max(map(len, bookdict.keys()))
authorwidth = max(map(len, bookdict.values()))
format迷你语言
还有这种迷你语言的用法:
template = '{{0:<{bw}}} {{1:>{aw}}}'.format(bw=bookwidth, aw=authorwidth)
for book, author in bookdict.items():
print( template.format(book, author) )
打印:
Little longer title here Author Name Here
Book Title Here Another Author Name Here
shorter here Diff Name Here
为了打破这一点,双括号将保留在第一种格式上并减少为单括号,并且单括号将成为计算的最大镜头的宽度,例如:
'{0:<30} {1:>20}'
小于 (<) 表示左对齐,大于 (>) 表示右对齐。
rjust 和 ljust
如果你真的想使用 str.rjust 和 str.ljust 方法:
for book, author in bookdict.items():
print(book.ljust(bookwidth) + ' ' + author.rjust(authorwidth))
打印:
Little longer title here Author Name Here
shorter here Diff Name Here
Book Title Here Another Author Name Here