Sujet : Re: Is there a better way? [combining f-string, thousands separator, right align]
De : PythonList (at) *nospam* DancesWithMice.info (dn)
Groupes : comp.lang.pythonDate : 26. Aug 2024, 10:42:32
Autres entêtes
Organisation : DWM
Message-ID : <mailman.8.1724661765.2917.python-list@python.org>
References : 1 2
User-Agent : Mozilla Thunderbird
On 26/08/24 03:12, Gilmeh Serda via Python-list wrote:
Subject explains it, or ask.
This is a bloody mess:
s = "123456789" # arrives as str
f"{f'{int(s):,}': >20}"
' 123,456,789'
With recent improvements to the expressions within F-strings, we can separate the string from the format required. (reminiscent of FORTRAN which had both WRITE and FORMAT statements, or for that matter HTML which states the 'what' and CSS the 'how')
Given that the int() instance-creation has a higher likelihood of data-error, it is recommended that it be a separate operation for ease of fault-finding - indeed some will want to wrap it with try...except.
>>> s = "123456789" # arrives as str
>>> s_int = int( s ) # makes the transformation obvious and distinct
>>> s_format = ">20," # define how the value should be presented
>>> F"{s_int:{s_format}}"
' 123,456,789'
Further, some of us don't like 'magic-constants', hence (previously):
>>> S_FIELD_WIDTH = 20
>>> s_format = F">{S_FIELD_WIDTH},"
and if we really want to go over-board:
>>> RIGHT_JUSTIFIED = ">"
>>> THOUSANDS_SEPARATOR = ","
>>> s_format = F"{RIGHT_JUSTIFIED}{S_FIELD_WIDTH}{THOUSANDS_SEPARATOR}"
or (better) because right-justification is the default for numbers:
>>> s_format = F"{S_FIELD_WIDTH}{THOUSANDS_SEPARATOR}"
To the extreme that if your user keeps fiddling with presentations (none ever do, do they?), all settings to do with s_format could be added to a config/environment file, and thus be even further separated from program-logic!
-- Regards,=dn