【问题标题】:Aligning strings with .format() [duplicate]使用 .format() 对齐字符串 [重复]
【发布时间】:2016-11-05 03:22:24
【问题描述】:

我有一些字符串要打印出来,我想对齐它们以使它们看起来整洁。

colours = ["Red", "Green", "Yellow"]
quantities = {"Red" : 6, "Green" : 4,  "Yellow" : 9

这是我目前打印出来的方式:

for colour in colours:
  print("{}: {}".format(colours[colour], quantities[colour]))

但是它们看起来像这样:

Red: 6
Green: 4
Yellow: 9

当我希望他们像这样出来时:

Red:      6
Green:    4
Yellow:   9

【问题讨论】:

    标签: python string python-3.x formatting alignment


    【解决方案1】:

    (纠正代码中的一些错误)...您可以使用 \t 插入制表符

    for colour in colours:
      print("{}:\t {}".format(colour, quantities[colour]))
    

    【讨论】:

    • 对不起,但这在我的代码中不起作用,我已经研究过使用 ljust() 但我不确定这是否可行......
    • 你能告诉我们当你尝试使用 \t 标签时会发生什么吗?
    猜你喜欢
    • 2014-01-07
    • 2016-10-26
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 2022-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多