How to format your strings in Python

Python offers several main ways to format your strings:

  1. Using + operator between elements to create a string, eg name + " is " + age + " years old"
  2. Using curly braces and format like "{} is {} years old".format(name,age)
  3. Using f strings like f"{name} is {age} years old"
  4. Using join like " ".join(name, age)
  5. Using % operator like "%s is %s years old" % (name, age)

Those are a lot of options. Try using all 5 of them in a Jupyter notebook, and set the name variable and the age variable. Age variable will obviously be an integer.

Two of these can be thrown out immediately. The .join() and + operators only work when the input is a string. For this reason you should not use them.

Now we are left with format, %, and f strings. Of these three options, I argue you should basically always use the f string because it makes it very clear where the variables go, especially when you have a long string. It is easier to understand and more robust.

In short, the Python foundation should set weak warnings for + operators and the join function because they are unstable. You should use the f string in all future string concatenation exercises.

Leave a comment

Discover more from Stidmatt

Subscribe now to keep reading and get access to the full archive.

Continue reading