Is there a better way? [combining f-string, thousands separator, right align]

dn PythonList at DancesWithMice.info
Mon Aug 26 04:42:32 EDT 2024


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


More information about the Python-list mailing list