Discussion:
Formatted Integer With Specified Number Of Digits
(too old to reply)
Lawrence D’Oliveiro
2025-10-19 07:26:44 UTC
Permalink
"%#0.3x" % 2
'0x002'

No equivalent to this in any of the other ways that Python allows for
format(2, "#03x")
'0x2'

(Not what I want)
format(2, "#0.3x")
Traceback (most recent call last):
File "<python-input-10>", line 1, in <module>
format(2, "#0.3x")
~~~~~~^^^^^^^^^^^^
ValueError: Precision not allowed in integer format specifier
"{:#03x}".format(2)
'0x2'

(Not what I want)
"{:#0.3x}".format(2)
Traceback (most recent call last):
File "<python-input-13>", line 1, in <module>
"{:#0.3x}".format(2)
~~~~~~~~~~~~~~~~~^^^
ValueError: Precision not allowed in integer format specifier

Why not?
Gilmeh Serda
2025-10-19 09:17:04 UTC
Permalink
Post by Lawrence D’Oliveiro
Why not?
I have no idea
Post by Lawrence D’Oliveiro
f"magic number: {'42'.zfill(4)}"
'magic number: 0042'
Post by Lawrence D’Oliveiro
f"magic number: {str(42).zfill(4)}"
'magic number: 0042'

more info:
https://fstring.help/cheat/
--
Gilmeh

Necessity is a mother.
songbird
2025-10-19 14:01:16 UTC
Permalink
Post by Lawrence D’Oliveiro
"%#0.3x" % 2
'0x002'
No equivalent to this in any of the other ways that Python allows for
format(2, "#03x")
'0x2'
(Not what I want)
format(2, "#0.3x")
File "<python-input-10>", line 1, in <module>
format(2, "#0.3x")
~~~~~~^^^^^^^^^^^^
ValueError: Precision not allowed in integer format specifier
"{:#03x}".format(2)
'0x2'
(Not what I want)
"{:#0.3x}".format(2)
File "<python-input-13>", line 1, in <module>
"{:#0.3x}".format(2)
~~~~~~~~~~~~~~~~~^^^
ValueError: Precision not allowed in integer format specifier
Why not?
https://github.com/tpauldike/printf


songbird
Lawrence D’Oliveiro
2025-10-19 21:39:17 UTC
Permalink
Post by Lawrence D’Oliveiro
"%#0.3x" % 2
'0x002'
No equivalent to this in any of the other ways that Python allows for
Why not?
We already have printf-style formatting in Python, that’s what I was using
above.
Paul Rubin
2025-10-24 08:14:39 UTC
Permalink
Post by Lawrence D’Oliveiro
"%#0.3x" % 2
'0x002'
f'0x{2:03x}
Alan Bawden
2025-10-24 10:38:05 UTC
Permalink
Post by Lawrence D’Oliveiro
"%#0.3x" % 2
'0x002'
f'0x{2:03x}

Won't work for negative numbers.
--
Alan Bawden
Loading...