Thursday, November 18, 2021

"Mathspp Pydon'ts": String formatting comparison | Pydon't 🐍

This article compares the three main string formatting methods in Python and suggests which methods to use in each situation.

Python snippet showing the three main ways of doing string formatting in Python.

(If you are new here and have no idea what a Pydon't is, you may want to read the Pydon't Manifesto.)

Introduction

The Zen of Python says that

“There should be one – and preferably only one – obvious way to do it.”

And yet, there are three main ways of doing string formatting in Python. This Pydon't will settle the score, comparing these three methods and helping you decide which one is the obvious one to use in each situation.

In this Pydon't, you will:

  • learn about the old C-style formatting with %;
  • learn about the string method .format;
  • learn about the Python 3.6+ feature of literal string interpolation and f-strings;
  • understand the key differences between each type of string formatting; and
  • see where each type of string formatting really shines.

You can now get your free copy of the ebook “Pydon'ts – Write beautiful Python code” on Gumroad.

String formatting rationale

Let's pretend, for a second, that Python had zero ways of doing string formatting.

Now, I have a task for you: write a function that accepts a programming language name and returns a string saying that said programming language rocks. Can you do it? Again, without any string formatting whatsoever!

Here is a possible solution:

def language_rocks(language):
    return language + " rocks!"

# ---
>>> language_rocks("Python")
'Python rocks!'

Great job!

Now, write a function that accepts a programming language name and its (estimated) number of users, and returns a string saying something along the lines of “ rocks! Did you know that has around users?”.

Can you do it? Recall that you are not supposed to use any string formatting facilities, whatsoever!

Here is a possible solution:

def language_info(language, users_estimate):
    return (
        language + " rocks! Did you know that " + language +
        " has around " + str(users_estimate) + " users?!"
    )

# ---
>>> language_info("Python", 10)
'Python rocks! Did you know that Python has around 10 users?!'

Notice how that escalated quite quickly: the purpose of our function is still very simple, and yet we have a bunch of string concatenations happening all over the place, just because we have some pieces of information that we want to merge into the string.

This is what string formatting is for: it's meant to make your life easier when you need to put information inside strings.

Three string formatting methods

Now that we've established that string formatting is useful, let's take a look at the three main ways of doing string formatting in Python.

First, here is how you would refactor the function above:

# Using C-style string formatting:
def language_info_cstyle(language, users_estimate):
    return (
        "%s rocks! Did you know that %s has around %d users?!" %
        (language, language, users_estimate)
    )

# Using the Python 3 `.format` method from strings:
def language_info_format(language, users_estimate):
    return "{} rocks! Did you know that {} has around {}...


from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...