…so I’m working on a data base of “Examples, Tricks and Tips” to be mounted using a WordPress plug-in called WP Data Access. I really hope it works out like it seems it will. In the process I’ve tackled an f-string problem that has too much utility to bury it in a database – how to use one statement (probably in a function to print, right aligned, a column of dollars and cents. The devil is in a careful reading and understanding of the term “replacement field”. A few lines of code will save many paragraphs of explanation:
random_data=[9876.5432,123.45,65.7,10543.21, -9183.765] detail_string = " =12,.2f" summary_string = "=10,.0F" for num in random_data: print(f"{'$'}{num:{detail_string}}") print("-"*13) print(f"{'$'}{sum(random_data):{detail_string}}") print() for num in random_data: print(f"{'$'}{num:{summary_string}}") print("-"*11) print(f"{'$'}{sum(random_data):{summary_string}}")
Changeing only the mini-language string this will produce:
$ 9,876.54
$ 123.45
$ 65.70
$ 10,543.21
$- 9,183.76
————-
$ 11,425.14
$ 9,877
$ 123
$ 66
$ 10,543
$- 9,184
———–
$ 11,425