如何根据 python 3.xx 列表中最大单词的长度右对齐输出

How to right align the output according to the length of the largest word in a list in python 3.xx

我有:

a = ['bicycle','airplane','car','boat']

for i in a:
    print("{:>??}".format(i)) # ?? because I dont know what to do here

我想要的输出:

  bicycle
 airplane
      car
     boat

我需要对齐我的输出,使所有单词都与最长单词一样大的间距正确对齐?? (我有一个问号,因为我认为这是实现我想要的输出的唯一方法)。谢谢。

选项 1
Pre-compute 最大字符串的长度并将其作为单独的参数传递给 format.

l = len(max(a, key=len))

for i in a:
    print("{n:>{w}}".format(n=i, w=l))

 bicycle
airplane
     car
    boat

选项 2
使用 str.rjust 的替代方法:

for i in a:
    print(i.rjust(l))  # same `l` as computed in Option 1


 bicycle
airplane
     car
    boat

选项 3
您还可以打印 pd.Series.to_string:

的转储
import pandas as pd
print(pd.Series(a).to_string())

0     bicycle
1    airplane
2         car
3        boat

其他的制表包(我用的tabulate)这里也可以使用效果不错