String formatting

What we cover in this chapter will only work with Python 3.6 or higher. If you are using repl.it make sure you use the correct version of Python!

Before Python 3.6, string formatting could be quite tricky. As of Python 3.6, it's been made much simpler.

What is string formatting?

We've learned that we can't add a string and a number together. String formatting helps us create a string that contains numbers (or anything else) without having to previously convert everything to strings.

String formatting also helps us do a few other things, but we will learn about those in due course.

Here's how to re-write the program we had in the last chapter using string formatting:

The key difference is this:

months = 360
print(f"Your age in months is: {months}")
1
2

The f in front of our quotation marks tells Python this is an f-string (formatted string).

We can then include {months} inside our string, and Python will replace it by the value of our variable.

WARNING

Make sure to place the f in front of the string, and not inside the string as the first character.

Multiple variables

Inside a single f-string we can place many variables, as long as each one has its own set of curly braces and name:

age = 30
months = age * 12
print(f"You are {age} years old, or {months} months.")
1
2
3

Other ways of doing string formatting

If you've learned Python in the past, you may have learned about formatting with % signs or with the .format() method. As of Python 3.6, f-strings is the recommended way.

We will talk about .format() later on in the course if it becomes necessary.

Extra reading

We've written a quick blog post with a few examples of different types of string formatting. If you want a glance at what other ways of doing string formatting exist, this is a good read: http://blog.tecladocode.com/learn-python-string-formatting-in-python/

RealPython has a comprehensive blog post, but it can be rather tricky because they also talk about other forms of string formatting and assume more knowledge of Python than you may have at this point.

If you're keen on progressing quickly and learning Python by exercise, this blog post may confuse you more than help you, but if you want some detailed reading this is an excellent choice: https://realpython.com/python-f-strings/

This is a great blog post filled with examples. Some examples are more complicated than others—don't feel the need to know what all of them do!

This is another guide with many examples. In addition to including variables inside strings, they also cover how to include dates which is not something we've looked at yet.

Last updated: 12/6/2018, 11:59:42 AM