在Python中添加字符串格式化的空白。

问题描述 投票:0回答:1

我试图理解下面代码的行为.当我增加第一个大括号中的数字时,我在第一列的左边得到了额外的空白。当我增加第二个数字时,我也得到了额外的空白,但在第二列的左边。然而,当我对第三个数字进行操作时,没有任何变化。为什么会这样呢?

w = ['storm', 'ubuntu', 'singular', 'pineapple']
for i, word in enumerate(w):
    word_index = 3
    print('{:2} {:1} {:6}'.format(i, word_index, word))
python string whitespace
1个回答
3
投票

默认情况下,数字向左垫,但字符串向右垫 (文件):

>>> "{:3}".format(1)
'  1'
>>> "{:3}".format("1")
'1  '

如果你想让字符串也向右对齐,请指定它。

>>> "{:>3}".format("1")
'  1'

注意,"风暴"(长度为5) 是否 实际上,当填充到宽度为6时,会得到一个额外的尾部空间,但由于它是打印在右边,你可能不会注意到。


1
投票

实际上有些东西确实发生了变化,但你看不到它。让我们使用一个稍微修改过的版本,标记输出的边距。

w = ['storm', 'ubuntu', 'singular', 'pineapple']
for i, word in enumerate(w):
    word_index = 3
    print('>>{:2} {:1} {:6}<<'.format(i, word_index, word))

当你运行这个,你会得到:

>> 0 3 storm <<
>> 1 3 ubuntu<<
>> 2 3 singular<<
>> 3 3 pineapple<<

现在,让我们把第三个宽度改为16。

w = ['storm', 'ubuntu', 'singular', 'pineapple']
for i, word in enumerate(w):
    word_index = 3
    # Changed width of 3rd field from 6 to 16
    print('>>{:2} {:1} {:16}<<'.format(i, word_index, word))

运行这个会在最后一个字段后提供更多的白色空间。

>> 0 3 storm           <<
>> 1 3 ubuntu          <<
>> 2 3 singular        <<
>> 3 3 pineapple       <<
© www.soinside.com 2019 - 2024. All rights reserved.