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 ๐
mathspp.com/blog/pydonts/sโฆ
I'm currently working on a string formatting case study.
What I mean is, I will take an old Python project that is used in real life...
But that uses only %-formatting.
And I will review the whole thing, upgrading the string formatting as I go.
Then, I will write a full article explaining
๐ what I did
๐ where I decided to use f-strings and where I decided to use `.format`
๐ why I made those decisions
Sounds interesting?
Then subscribe to my newsletter to stay in the loop ๐
mathspp.com/subscribe
TL;DR:
๐ f-strings are generally better than `.format`:
shorter & more expressive
๐ %-formatting should be avoided:
old & less features
๐ do modern alignment with <^>
๐ .format is nicer than f-strings when data is in a dictionary with string keys
See you around ๐
Share this Scrolly Tale with your friends.
A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.