The Whole Story About f-strings in Python

If you use Python frequently then you might know that f-strings are an easy way of adding variables into a string, and while that is correct it has a few more features.

Juan Velasquez
Age of Awareness

--

Variable substitution

The classic: placing a variable inside the curly brackets substitutes it with its value into the string.

Variable’s name = variable’s value

Adding an equal symbol = to the end of the variable will add its name and its value like in a declaration expression. (Available in Python 3.8+)

This could be helpful specially for debugging. You could also add spaces and even expressions to evaluate.

Conversions

Adding !a , !r or !s at the end of the variable will apply its specific functionality before returning the string.

  • !a: stands for ASCII, all non-ASCII characters get replaced by an ASCII safe escaped version of it.
  • !r: stands for repr , and it basically takes the returned string from the repr function of the variable.
    Side note: repr() is a method that returns the string representation of an object.
  • !s: this is the default, so it basically turns whatever your variable contains into a string.

Advanced formatting

Using the conversions we saw before you can implement a __format__ method in a class so it can support advance formatting. Some classes like datetime , float and int have this feature.

You can find more about format codes for a datetime object here. Clearly for each data type this is different and it needs to be checked before using it. Let’s see another example with more common types.

For integers the number zero specifies that the format should include leading zeros and the second number specifies the number of digits it should contain.

For floating numbers the formatting provides a rounding feature that can be used as shown above. Using a dot followed by the number of digits after the comma, followed by an “f”.

Conclusion

F-strings help keeping the code short and readable, but they can also do much more than that. You can add a __format__ method to your class and give it extra features to format the way its objects convert to strings.

--

--

Juan Velasquez
Age of Awareness

Software developer. Python. Automation tester. Microelectronics. Twitter: @__jvelasquez__