【问题标题】:Adding whitespaces to Python 3 format string using number of digits of integer使用整数位数向 Python 3 格式字符串添加空格
【发布时间】:2022-07-25 20:24:53
【问题描述】:

以下问题: How to set the spaces in a string format in Python 3

为什么第一个有效,第二个无效?

string='Hello World!'
length = 20
print('{1:>{0}}'.format(length, string))

结果: Hello World!

string='Hello World!'
length = len(string)
print('{1:>{0}}'.format(length, string))

结果:Hello World!

【问题讨论】:

    标签: python string integer format output


    【解决方案1】:

    你的两个 sn-ps 应该都能正常工作。您收到不同输出的原因是第一个示例中的长度为 20,但在第二个示例中为 12。因为你的长度总是和你的字符串一样长,所以你永远不会看到额外的空格。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-21
      • 2011-08-27
      • 2021-07-09
      • 1970-01-01
      • 2013-05-16
      • 1970-01-01
      相关资源
      最近更新 更多