4 String Formatting Techniques in Python — Feel the Evolution
See the big picture and find your favourite one
Python is a rapidly evolving language.
In the old days (Python 2.x), its string formatting syntax brought the idea from the C language. You have to use the “%” operator, whose syntax is not elegant enough and may cause ugly code, for string formatting.
Since Python 3.x, a new built-in method called format() was introduced and made things neater.
From Python 3.6, the birth of formatted string literals, so-called f-strings, made a great stir in the Python community.
This article will summarise the 4 common ways for string formatting in Python. After reading, you can see the big picture, feel the evolution of Python, and most importantly, find the right way for your programs.
0. C Style String Formatting with the “%” Operator
If you started to use Python since its 2.x version, you definitely know this printf-style string formatting syntax. It’s kind of old-school but still available for the latest Python version.
For example, the following code print a string including another string variable:
name='Yang'
print("Hi, %s" %name)
# Hi, YangOr print a formatted number:
protocol=7
print("Hi, %03d" %protocol)
# Hi, 007There are more complicated usages for this method. But the problem is that you probably need to save the official reference to your bookmarks. Cause it’s too hard to remember all syntax details.
In addition, even the official document said that using newer formatting ways may avoid some unexpected errors:
The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer formatted string literals, the str.format() interface, or template strings may help avoid these errors.
1. Using the Built-in Format Function
Since Python 3, every Python string has a built-in function named format() to do formatting stuff.
Let’s use this function to rewrite the previous examples:
name='Yang'
print("Hi, {}".format(name))
# Hi, YangAnd for printing the number:
protocol=7
print("Hi, {:03}".format(protocol))
# Hi, 007This syntax brought some new tricks. Such as the usages of placeholders:
name='Yang'
desc='amazing'
print("Hi, {n}! You are {d}!".format(n=name,d=desc))
# Hi, Yang! You are amazing!2. Formatted String Literals: the F-Strings
The format() function is much better, but still not elegant enough.
But since Python 3.6, the appearance of the f-strings made the string formatting really Pythonic.
What does Pythonic mean?
It means shorter, cleaner, neater, and better.
Let’s rewrite the same example again:
name='Yang'
desc='amazing'
print(f"Hi, {name}! You are {desc}!")
# Hi, Yang! You are amazing!Or print a specific number:
name='Yang'
protocol=7
print(f"Hi, {name}! You are {protocol:03d}!")
# Hi, Yang! You are 007!Or even run a function inside your string! 😎
