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?
CodePudding user response:
Are the underscores that annotate the integer stored at any point for downstream use
No, they're purely a syntactic convenience.
You should just format your values using a real formatter:
import locale
locale.setlocale(locale.LC_ALL , 'en_CA') # E.g. for Canada
print(locale.format_string('%d', 1234567, grouping=True)) # 1,234,567
As a bonus, it can be made it be correct of the user's locale (e.g. many places use spaces for separators in stead of commans, and commas instead of the period for the decimal point).
CodePudding user response:
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'