2 years ago

#57957

test-img

ElRudi

String formatting not working when accessed through dictionary

I try to create a dictionary of string formatting lambda functions, but for some (to me) obscure reason, it's not working, and the incorrect value is retrieved from the dictionary; see the use of the ffuncs dictionary, below.

value = 12345.6789

fstrings = {"a": "{:,.2f}", "b": "{:,.5f}"}
print(fstrings["a"].format(value).replace(",", " "))  # 12 345.68

ffuncs = {}
for key, fstring in fstrings.items():
    ffunc = lambda v: fstring.format(v).replace(",", " ")
    ffuncs[key] = ffunc
    if key == "a":
        print(id(ffunc))  # 2020101253584
        print(ffunc(value))  # 12 345.68  <-- here it's still working

print(id(ffuncs["a"]))  # 2020101253584 <-- same function...
print(ffuncs["a"](value))  # 12 345.67890 <-- ...but 5 decimal places??

Seems incredibly basic, but I can't figure it out. Many thanks.

python

lambda

string-formatting

0 Answers

Your Answer

Accepted video resources