When I use f-strings with a format-specifier in a way like
>>> x = 1
>>> f'{ x:02 }'
It gives me ValueError: Unknown format code '\x20' for object of type 'int'
. To fix this, I have to remove the surrounding whitespaces from the f-string expression, like f'{x:02}'
.
Why is this so?
Given an f-string expression such as f'{ x:02 }'
, the format specifier portion of the expression starts and includes all characters after the colon (:
). This means that the space to the right of 02
is part of the format specifier. Despite what the error says, as said by Chris Rands, a space is a valid format code. What causes the error is that we used an invalid format specifier for an integer. Adding a space after 02
invalidates the specifier.
We can fix the problem with
>>> f'{ x:02}'
which successfully got me 01
. However, I subjectively do not recommend this style for f-string expressions since it looks imbalanced, i.e. the leftmost space has no pairing space at the other end of the expression. I would not use any surrounding spaces instead (e.g. f'{x:02}'
).
Recommended Reading
EDIT: I edited this answer to provide the correct explanation. In a previous edit, I incorrectly stated that a space is not a valid code in a format. Thanks, Chris, for the correction.