3 Tips for Advancing Python String Formatting

Start using f-string to align code and make strings readable, clean, and explicit

Hannibal Liang
Mar 19, 2020 · 3 min read
Image for post
Image for post
Photo by Taylor Vick on Unsplash

String formatting means embedding expressions inside string literals. In most of the Python tutorials for beginners, the first task starts with the “Hello World” project, which makes string the most familiar variable type.

However, once you start adding parameters inside a longer string, your code would be less concise and readable. For example:

Obviously, the string concatenation looks bad and wordy, so the Python Software Foundation invented a function called .format() to shorten the syntax:

It’s more intuitive but still not easily readable, so why not adopt new ways?
By the end of this article, you will learn three ways to keep your code concise:

  1. Formatted string literals.

What Are Formatted String Literals?

Formatted string literals (f-string) feature a simple syntax and shorter expressions, which replace “old school” methods like %-formatting or str.format().

Even better, it executes faster than these old methods, and the clue is provided in PEP 498:

“F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is really an expression evaluated at run time, not a constant value.”

In short, f-string uses fewer bytecode instructions than other methods. If you are interested in the advanced interpretation of f-string, check out the Python docs.

To show how f-strings work. Let’s reuse the example above:

The string has an f at the beginning and curly braces involving expressions replaced with their values. This technique can also cooperate with dictionary/class/list.

Furthermore, f-string supports various format specifications to eliminate excessive work, while the syntax remains concise.

How to Implement Output Alignment

How much time have you spent on counting digits of numbers to distinguish the exact value?

In the real world, we are unconsciously affected by how the texts are formatted and expect nice alignment for a comfortable reading experience. In Python’s output display, we have powerful tools for doing so:

  1. Commas “,” to separate groups of thousands.

2. Limited digits to display lengthy numbers.

3. Space padding to align the paragraphs.

These examples are the commonly used specifications, and other options can be found in Python’s official docs, including showing positive or negative signs, changing positional systems, and displaying percentage signs.

Because the notations are too massive to remember, using the cheat sheet is always the right choice.

Assuming that the paragraph about f-strings isn’t enough for you, try this one!
(I’ve always been a big fan of Real Python!)

Why Is Maximum Line Length Important?

Don’t stress the reader by sticking too much code in one line. A recommended maximum line length is 79 characters according to the Style Guide for Python Code.

The limitation of the editor window width works well when using code review tools. Whenever you want to copy codes from one file to another or use Git to compare two code versions, the controlled window length makes it possible to have several files open side-by-side.

https://medium.com/analytics-vidhya/how-to-download-images-faster-using-multithreading-in-python-a31110468770
https://medium.com/analytics-vidhya/how-to-download-images-faster-using-multithreading-in-python-a31110468770
Download images agiler from Unsplash using Python.

Conclusion

The ability to simplify means to eliminate the unnecessary so that the necessary may speak. String formatting won’t cause any effect on your algorithm, but it is gentle to make others comfortable while reading your code.

For more tips to make code nice and tidy:

Thanks for reading! I hope you enjoyed it.

Better Programming

Advice for programmers.

Sign up for The Best of Better Programming

By Better Programming

A weekly newsletter sent every Friday with the best articles we published that week. Code tutorials, advice, career opportunities, and more! Take a look

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Hannibal Liang

Written by

Dreaming of making programming more concise and decent.

Better Programming

Advice for programmers.

Hannibal Liang

Written by

Dreaming of making programming more concise and decent.

Better Programming

Advice for programmers.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store