Search code examples
pythonstring-formatting

Maintain underscore separators' positions when printing f-string


If I have an amount like $40,000.00 I might want to make this more readable in code by writing the number with underscore separators

deposit = 40_000_00

I know I can use the following syntactic sugar for formatting f-strings but this prints a thousands-separated integer (4_000_000)

print(f"{deposit:_}")
# 4_000_000

Are the underscores that annotate the integer stored at any point for downstream use, or would I simply need to use an appropriate class with a __repr__ to achieve the desired effect?


Solution

  • This is impossible. As detailed in the PEP515 that you cited:

    The underscores have no semantic meaning, and literals are parsed as if the underscores were absent.

    Thus the resulting python object has no knowledge that those underscores where ever there.

    If you need to store a custom separator, be explicit. Use a string.

    deposit = '40_000_00'