Search code examples
pythonformattingf-string

Print arg name with format strings for debug output


It is common to use format strings (or f-strings) to print variables for debugging. However one needs to repeat the argument names if they should be printed as well.

[first_name, last_name, age] = ["Randall", "Munroe", 37]
print(f"first_name={first_name} last_name={last_name} age={age}")

Is there a shorter way to produce the same (or similar) output of names and values with f-strings?

I believe I have seen a short form however I did not find any mention in the format string syntax.


Solution

  • A shorter form (aka "shorthand") is to write {a=}instead of a={a}.

    [first_name, last_name, age] = ["Randall", "Munroe", 37]
    print(f"{first_name=} {last_name=} {age=}")