【问题标题】:Python: Format placeholder multiple times for the same variablePython:为同一个变量多次格式化占位符
【发布时间】:2014-01-29 14:37:09
【问题描述】:

我想同时执行填充和限制将使用 .format 输入到字符串中的变量的小数点数。我设法限制了小数位,但我似乎也无法添加填充。 documentation 没有多大帮助。以下是我的代码的副本。

print "Frame No. {:6d} Expected: {:7.3f}ms Actual: {:7.3f}ms Difference: {:7.3f}ms - ERROR".format(currentImage, expected_time, regression_obj.timeFromStart, (regression_obj.timeFromStart - expected_time))

这里的输出显示值之间没有足够的空格。我希望所有值都对齐。

Frame No.     17 Expected: 582.080ms Actual: 484.971ms Difference: -97.109ms - ERROR
Frame No.     18 Expected: 616.320ms Actual: 513.498ms Difference: -102.822ms - ERROR

预期输出;

Frame No.     17 Expected:       582.080ms Actual:     484.971ms Difference:   -97.109ms - ERROR
Frame No.     18 Expected:       616.320ms Actual:     513.498ms Difference:  -102.822ms - ERROR

【问题讨论】:

  • 那么问题是值之间没有足够的空间?
  • 你的预期输出是什么?
  • @wnnmaw 是的,请参阅问题中的编辑
  • @tayfun 输出应该都是内联的,请参阅问题中的编辑。
  • 次要,但让我感到困惑:“内联”意味着“嵌入”。您的意思是“对齐”,或者更好的是“对齐”。

标签: python string format


【解决方案1】:

使用{:9.3f}。第一个数字是整个数字的最小宽度,包括减号、小数点和小数位。

在您的示例中,-102.822 已经是 8 个字符,因此当您指定宽度为 7 时它会不对齐。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    • 1970-01-01
    • 1970-01-01
    • 2019-11-20
    相关资源
    最近更新 更多