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 πŸ‘‹

β€’ β€’ β€’

Missing some Tweet in this thread? You can try to force a refresh
γ€€

Keep Current with Rodrigo πŸπŸ“

Rodrigo πŸπŸ“ Profile picture

Stay in touch and get notified when new unrolls are available from this author!

Read all threads

This Thread may be Removed Anytime!

PDF

Twitter may remove this content at anytime! Save it as PDF for later use!

Try unrolling a thread yourself!

how to unroll video
  1. Follow @ThreadReaderApp to mention us!

  2. From a Twitter thread mention us with a keyword "unroll"
@threadreaderapp unroll

Practice here first or read more on our help page!

More from @mathsppblog

6 Nov
The Python 🐍 Standard Library is one of the reasons I love πŸ’™ Python.

πŸ“‚πŸ” dealing with your filesystem is super simple.

All you have to do is use the `pathlib` module.

This short thread is a mini `pathlib` cookbook 🍳, showing some example usages of `pathlib`.

Ready πŸš€?
πŸ“‚ Creating a `Path` object

`Path` objects are the bread and butter of `pathlib`.

Here, I just create a path with no arguments, which defaults to the path `.`

Notice how I used `Path` but I get a `WindowsPath` back.

`pathlib` automatically detects your OS πŸ˜‰
πŸ“‚ Getting the parent

The `parent` attribute returns the logical parent of the path you have at hands πŸ‘‡
Read 11 tweets
5 Nov
πŸ—“οΈ the weekend is coming πŸ₯³

If you want, use it to rest! You deserve it!

Or, make this a memorable weekend:

Let this be the weekend you implement your first neural network 🧠 from scratch, in Python 🐍

Here's the roadmap πŸ›£οΈ

πŸ‘‡πŸ§΅
By the time you are done, you'll have

πŸ‘‰ a minimal neural network framework
πŸ‘‰ solved a ML problem with accuracy > 90%

And all this with a surprisingly short amount of code!
First, we start with an appetizer.

It will spark your interest, and acquaint you with some terminology.

Your appetizer is this amazing video by @3blue1brown πŸ‘‡

Read 9 tweets
5 Nov
I gave you a Python 🐍 challenge πŸ†...

You delivered πŸ’ͺ!

This thread 🧡 will review some of your `argmax` implementations.

I'll also tell you what's good βœ… and bad ❌ about them.

I'll also tell you which one I think is the best, most Pythonic ✨ one.

Let's go πŸš€
The `argmax` function returns the index of the maximum element of the argument.

So, why don't we write this solution?

Compute the maximum, and then use `.index` to get its index! πŸ‘‡

But there are two issues here...

Can you see them? πŸ‘€
πŸ‘‰ first issue is that it traverses the argument twice;
(once to get the max, one more time to find its index)

πŸ‘‰ second issue is that it assumes the argument has a method `.index`, which might not be the case.

However, let's try and fix the first problem first...
Read 20 tweets
5 Nov
Python 🐍 objects have one important characteristic about them:

Some objects are mutable, which means their contents can be changed.

This ⚑🧡 will explain what (im)mutability means in Python 🐍.

Let's go πŸš€
The (im)mutability of an object depends on its type.

In other words, (im)mutability is a characteristic of types, not of specific objects!

For example,

πŸ‘‰ ALL integers are immutable.
πŸ‘‰ ALL lists are mutable.

With me so far?
But what exactly does it mean for an object to be mutable?

Or for an object to be immutable?

Recall that an object is characterised by

πŸ‘‰ its identity
πŸ‘‰ its type
πŸ‘‰ its contents.

I wrote about that in this thread πŸ‘‡

Read 13 tweets
1 Nov
Here is a Python 🐍 function that tells you if the input number is even or odd...

But how does it work? πŸ‘‡

It looks a bit weird, doesn't it?

Someone DM'd me this function from a @realpython article, and now this ⚑🧡 will break it down for you.

Here we go πŸš€
If you have heard of Boolean short-circuiting, that's the short answer:

Boolean short-circuiting is what's responsible for the behaviour of `f`.

Let me explain...

First, we need to understand the precedence of the `and` and `or`.

Let me add parentheses πŸ‘‡
`and` has higher precedence than `or`.

In other words, `and` β€œbinds tighter” to its operands than `or`.

Now, usually we use `and` and `or` with Boolean operands, to return a Boolean value.

However, `and`/`or` work with arbitrary objects as operands.

We call it,
Read 14 tweets
31 Oct
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.
Read 12 tweets

Did Thread Reader help you today?

Support us! We are indie developers!


This site is made by just two indie developers on a laptop doing marketing, support and development! Read more about the story.

Become a Premium Member ($3/month or $30/year) and get exclusive features!

Become Premium

Too expensive? Make a small donation by buying us coffee ($5) or help with server cost ($10)

Donate via Paypal

Thank you for your support!

Follow Us on Twitter!

:(