0

I just want to format a number as hex, with four characters in all - so up to three leading zeroes. I'm trying this:

$ python3 --version
Python 3.10.10

$ python3 -c 'TVAR=0x000a; print(f"{TVAR:#04x}")'
0x0a

So, I thought that with 04x I had specified string of total 4 characters to the f-string, padded left with zeroes if need be - but I only get a two-character hex formatted string.

Can I somehow modify this kind of f-string specification, so I get a 4-digit, left-zero padded, hex numeric string (in this case, 0x000a) - and if so, how?

sdbbs
  • 4,270
  • 5
  • 32
  • 87
  • Thanks, @Axe319 - ah, I had never met string formatting so far, that included the `0x` prefix in the number of characters in the specification! Thanks, that makes sense - and it works. Feel free to post this as an answer, I'll accept it – sdbbs Mar 21 '23 at 20:56

1 Answers1

0

From the docs:

The '#' option causes the “alternate form” to be used for the conversion. The alternate form is defined differently for different types. This option is only valid for integer, float and complex types. For integers, when binary, octal, or hexadecimal output is used, this option adds the respective prefix '0b', '0o', '0x', or '0X' to the output value.

And then later:

width is a decimal integer defining the minimum total field width, including any prefixes, separators, and other formatting characters. If not specified, then the field width will be determined by the content.

Note "including any prefixes".

And then finally:

When no explicit alignment is given, preceding the width field by a zero ('0') character enables sign-aware zero-padding for numeric types.

And for the x type:

Hex format. Outputs the number in base 16, using lower-case letters for the digits above 9.

Putting this all together, we can use:

TVAR = 0x000a
print(f"{TVAR:#06x}")

which outputs:

0x000a

Admittedly, I personally find the docs on the Format Spec mini-language hard to parse in certain sections as it involves a lot of jumping around to find a specific case you're interested in.

Axe319
  • 4,255
  • 3
  • 15
  • 31