Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `=` in Python's format function inserts padding after the prefix?

Why does the numeric alignment option = inserts padding after the prefix 0x in Python's format function:

>>> "{: =+#8x}".format(4)
'+0x    4'

i.e. why is the output '+0x 4' and not '+ 0x4'?

The docs are a bit ambiguous saying:

Forces the padding to be placed after the sign (if any) but before the digits.

Technically 0 in 0x is a digit, but 0x is treated in the same way as a sign in the above example.

like image 937
vitaut Avatar asked May 04 '26 12:05

vitaut


1 Answers

I would say that it is mostly useful with zero padding

Currently:

>>> "{:0=+#8x}".format(4)
'+0x00004'

But would you prefer: '+00000x4' ? I don't think so, as this isn't even a valid number

   +00000x4
          ^
SyntaxError: invalid syntax
like image 93
Jean-François Fabre Avatar answered May 06 '26 02:05

Jean-François Fabre