【发布时间】: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