Text formatting error: '=' alignment not allowed in string format specifier

前端 未结 6 1563
庸人自扰
庸人自扰 2020-12-30 19:24

What does \'=\' alignment mean in the following error message, and why does this code cause it?

>&         


        
6条回答
  •  臣服心动
    2020-12-30 20:00

    A workaround is to use '>' (right justify) padding, which is with the syntax:

    [[fill]align][width]
    

    with align being >, fill being 0 and width being 3.

    >>> "{num:0>3}".format(num="1")
    '001'
    

    The problem was that there is a different 0 in the format specification:

    format_spec     ::=  [[fill]align][sign][#][0][width][grouping_option][.precision][type]
    #                                          ^^^ This one
    

    That zero just makes fill default to 0 and align to =.

    = alignment is specified as:

    Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form ‘+000000120’. This alignment option is only valid for numeric types. It becomes the default when ‘0’ immediately precedes the field width.

    Source (Python 3 docs)

    This expects the argument to be an int, as strings don't have signs. So we just manually set it to the normal default of > (right justify).

    Also note that 0 just specifies the default values for fill and align. You can change both or just the align.

    >>> # fill defaults to '0', align is '>', `0` is set, width is `3`
    >>> "{num:>03}".format(num=-1)
    '0-1'
    >>> # fill is `x`, align is '>', `0` is set (but does nothing), width is `"3"`
    >>> "{num:x>03}".format(num=-1)
    'x-1'
    >>> # fill is `x`, align is '>', `0` is set (but does nothing), width is `"03"` (3)
    >>> "{num:x>003}".format(num=-1)
    'x-1'
    

提交回复
热议问题