Published on

String Interpolation in Python 3


Today I was working with some Python code and I needed to print out some variables for debugging purposes but I wanted to format these for better readability. I know other languages support string interpolation and Python is no exception either. This was actually really easy as can be seen below:

foo = 3
bar = 4
debug_string = f"foo [{foo}] bar [{bar}] foo + bar [{foo + bar}]"
# you can also obviously do this inline
# print(f"foo [{foo}] bar [{bar}] foo + bar [{foo + bar}]")

This outputs:

foo [3] bar [4] foo + bar [7]

I assume the f at the front of the string stands for format as in format string similar to Sprintf in Go.

In my example above the square brackets around each parameter are not required at all. This is something I tend to do when outputting variables for debugging. The square brackets allow you to easily see if the output variable is a non-visible string, a string with spaces or just null.