Tip 64 Format with Formatted Strings

Pythonic Programming — by Dmitry Zinoviev (76 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Build, Then Print | TOC | Import Wisely 👉

★★3.6+ Future digital archaeologists would study the history of Python by looking at its string formatting tools. At least four layers of them are all still in use, each progressively more sophisticated and efficient.

One of the original methods converts all future string fragments to strings with str and further string concatenation with the operator + (the numbers in the comments show the average statement execution time in milliseconds):

​ name = ​'Mary'​
​ ​'Hello, '​ + str(name) + ​', how is your lamb?'​ ​# 0.17​

The method is acceptable (but slow) if all fragments are already strings, in which case the call to str is more precautionary than necessary. However, if any fragment is a number whose precision and alignment you want to control, then str is not smart enough for that. Enter the substitution operator %. It is faster and more versatile. Despite a common belief, even in Python 2.7, it was used for string substitution, not for printing. Note the one-element tuple as the right operand of %. (And see Tip 33, Construct a One-Element Tuple.)

​ ​'Hello, ​​%​​s, how is your lamb?'​ % (name,) ​# 0.12​

The % placeholders in the body of the string allow a great deal of configuration and are, in general, compatible with the namesake mechanism in C/C++/Java. If…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.