Lesson Contents
Before Python 3.6, you had two options to format your strings:
- % formatting.
- str.format().
The F-string formatting option has been available since Python 3.6.
In this lesson, I’ll show you why the older % formatting and str.format() options to format your strings are obsolete nowadays and how the F-string formatting option makes your life much easier.
% Formatting
The %-formatting option has been available since the beginning of Python. The % operator is built into string objects. You can use this to format strings. For example:
You can use the % operator multiple times, but you’ll need to use a tuple () to supply the values you want to use to format your string:
If you only want to format your strings with one or two values, the % operator works fine. However, with many values to replace, your code becomes difficult to read:
In the code above, you can see the problem with the % operator. Your code becomes difficult to read because you can’t really tell which value replaces what % symbol.
str.format()
Python 3 has a newer way to format strings by using .format() on a string object. Here is a quick example that looks similar to the old %-formatting method.
It is possible to specify the values you want to use to format your strings within the strings:
This makes your code easier to read than the % formatting method. However, if you have many things in your string that you want to format, your code becomes messy:
F-Strings
F-strings are easy to work with and keep your code readable. Here is a quick example:
Before the string, you add an “f”. This can be a small or capital letter. You can then add whatever you want to format in between {}
. A huge advantage of this way of formatting is that your code remains easy to read, even when you want to format many things in your string. For example:
Python Expressions
I used variables like “vendor” or “platform” with assigned strings in the examples above. Python evaluates f-strings at runtime, allowing you to run any valid Python expressions in a string. Here is an example:
In the example above, I use an arithmetic operator (division) in the f-string.
Here is one more example where I use the title()
method:
Being able to use expressions in your code can help to keep your code nice and clean.
Conclusion
In this lesson, you have learned how f-strings work and why this is a better option than the %-operator or str.format()
method. There is more that you can do with f-strings, but this should be enough to get you started. You can read more about it in PEP 498.
I hope you enjoyed this lesson. If you have any questions feel free to leave a comment!