I have been tweeting about Python π string formatting.
I have been preaching π that f-strings are the best string formatting alternative.
Then comes the string method `.format`.
And only then, %-formatting.
Here is a thread 𧡠comparing the 3 π
In its most basic form,
π %-formatting uses % and a letter inside the string
π `.format` replaces sequences of {} with the data
π f-strings use {} to insert the data _inside_ the string
Here is how it looks like π
An undervalued feature of string formatting is that you can easily determine whether your data should be formatted with its string (str) or with its representation (repr).
For debugging, `repr` is usually more useful.
Here is how this looks like π
Aligning the data inside a field is also much easier with `.format` and f-strings.
For one, %-formatting can't handle centre alignment.
Secondly, with `.format` and f-strings you just use <^>, which points to where the alignment should be!
Easy to remember π€πβ
Now, to be fair, there are some situations when I think `.format` is better than f-strings.
Such an example is when we have the formatting data inside a dictionary, with string keys.
In that case, `.format` is great!
There is another situation in which `.format` and f-strings completely blow %-formatting out of the water.
With `.format` and f-strings, we can implement custom formatting specifiers for our own objects.
All we need is `__format__`!
Here is a (silly) demo π
These were just some comparison points between the three main ways of doing string formatting in Python.
I took these examples from a Pydon'ts article of mine, that you can read here π
Would you like me to teach you how to write Python π code that is more elegant, more effective, and more expressive than what you have been writing until now... for free?
I am looking to teach Python to people who want to master Python to the best of their abilities.
Do you? If you do, then I know I can help you improve your skills.
How do I know that?
My book has over 10,000 readers, and all of them have one thing in common: they are humans.
Python has dozens of built-ins, and all of them have multiple usage patterns. No human knows all of them by heart, but my research bundled them up nicely in a book for you to reference and learn from.