Rodrigo ๐Ÿ๐Ÿš€ Profile picture
Take your Python ๐Ÿ skills to the next level ๐Ÿš€!

Nov 21, 2021, 10 tweets

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.

Keep scrolling