【问题标题】:How do I adjust a string's field length with print formatting?如何使用打印格式调整字符串的字段长度?
【发布时间】:2020-02-20 11:45:44
【问题描述】:

我是初学者,我在 Udemy Python 课程中看到了这个我不理解的示例:

“在花括号内,您可以指定字段长度、左/右对齐方式、舍入参数等。”

print('{0:8} | {1:9}'.format('Fruit', 'Quantity'))
print('{0:8} | {1:9}'.format('Apples', 3.))
print('{0:8} | {1:9}'.format('Oranges', 10))

Fruit    | Quantity
Apples   |       3.0
Oranges  |        10

我不明白我在看什么,所以我试着像这样玩第一行来弄清楚规则:

print('{0:25} | {1:9}'.format('Fruit', 'Quantity'))

Fruit                     | Quantity

接下来我尝试了这个:

print('{0:8} | {1:25}'.format('Fruit', 'Quantity'))

Fruit    | Quantity                 

你看不到它,但如果你突出显示 Quantity 后面的空格,我似乎创建了一个等于 25 个空格的长度,包括单词。

没想到,减少数字并不会删除单词 Fruit 或 Quantity 中的字母:

print('{0:4} | {1:4}'.format('Fruit', 'Quantity'))

Fruit | Quantity

下一行似乎有与字符串 'Quantity' 不同的影响 float 3.0 的规则:

print('{0:8} | {1:9}'.format('Fruit', 'Quantity'))
print('{0:8} | {1:25}'.format('Apples', 3.))

Fruit    | Quantity 
Apples   |                       3.0

接下来我尝试减少浮动字段的长度。

print('{0:8} | {1:9}'.format('Fruit', 'Quantity'))
print('{0:8} | {1:1}'.format('Apples', 3.))

Fruit    | Quantity 
Apples   | 3.0

调整这个数字会在浮点数/整数之前放置空格,但如果可能的话,会在字符串末尾添加空格。查看第三行中的 10,似乎整数出现在定义的空格数的末尾。这是我对规则的猜测。

在网上有关于这种技术的解释吗?课程中没有进一步的解释,我不知道在谷歌上专门搜索什么。

感谢所有花时间阅读所有内容的人!

【问题讨论】:

    标签: python string formatting


    【解决方案1】:

    你没看错。作为一般规则,字符串左对齐,数字右对齐。如果表示一个字段所需的字符数超过了允许的空间,它将占用额外的空间。

    您可以使用“”调整每个字段的对齐方式。更多详情请查看this

    【讨论】:

      猜你喜欢
      • 2015-04-05
      • 1970-01-01
      • 2017-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多