Printing and F-Strings

Overview

Printing output and the formatting of strings are two key components of Python. Without these processes it becomes more difficult to debug code, communicate output to users, and format data in an understandable way. The two sections on printing and f-strings are included below.

Printing

The Python function print allows you to…​ well…​ print. Printing values and information about a program while the program is running is still to this day one of the best methods to debug your code. This is one of the many reasons to get comfortable with the print functionality in Python.

You can print simple string literals:

print("This is a simple string literal being printed.")
This is a simple string literal being printed.

You can also print other types of variables, not just strings:

print(int(4))
4
print(float(4.4))
4.4

You can even mix and match what you print:

print("This is a string and an int:", int(4))
This is a string and an int: 4
print("I cannot tell a lie:", False)
I cannot tell a lie: False

You can even do arithmetic inside the print function. The options are endless!

print("4+4=", 4+4)
4+4= 8

Escape Characters

In Python, as with many other programming languages, certain characters are protected or having other meanings when used in code. When you want to print these types of characters they must be escaped in the text so that Python can recognize that they shouldn’t have special meaning. These are called escape characters.

For example, Python has built in functionality that recognizes that \n is a newline character:

print("This is line 1.\nThis is line 2.")
This is line 1.
This is line 2.

Here are a couple more escape characters for reference:

print("This is a carriage return\rAs you can see it is not a visible character.")
This is a carriage return
As you can see it is not a visible character.
print("You can also tab!\tHow about two tabs?\t\tYou bet!")
You can also tab!   How about two tabs?     You bet!

Now that we know how Python recognizes some of these characters, what do you do if you actually want to print \n or \t? Thankfully we have a couple options:

print("You can escape a backslash with another backslash: \\")
You can escape a backslash with another backslash: \

Another example using a newline would be:

print("Show me a newline: \\n")
Show me a newline: \n

You can also add an r before the string. The r represents raw and will render the text literally:

print(r"Now the string is raw! \n \r")
Now the string is raw! \n \r

This can be very helpful when you want to use double or single quotes in your output. You can escape them using one of the techniques described above:

print("This sentance has \"double quotes\".")
This sentance has "double quotes".
print("This one has \'single quotes\'.")
This one has 'single quotes'.

You can also mix and match quote types in order to avoid having to escape the characters:

print('Now it is easy to print "double quotes".')
Now it is easy to print "double quotes".
print("The same thing works for 'single quotes'.")
The same thing works for 'single quotes'.

F-Strings

F-Strings are extremely straightforward, useful, and fast. I would highly recommend using f-strings when the need arrives to print more than simple text.

f-string stands for "format string". An f-string is a string literal that starts with an f or an F:

print(f'This is an f-string.')
This is an f-string.

Like other Python strings you can use double or single quotes as well as f or F.

print(F"This way works as well!")
This way works as well!

So why are f-strings worth it? They allow you to print expressions inline! This doesn’t sound like much but it can be amazingly helpful.

print(f"4+4={4+4}")
4+4=8

But even better, they allow you to call functions:

def sumthis(a, b):
    return(a + b)

print(f"4+4={sumthis(4,4)}")
4+4=8

You can even write multi-line f-strings. Although you do need to be sure to add an f before each line:

first = 'First'
second = 'Second'

multiline_string = f"First line {first}."\
                   f"Second line {second}."
print(multiline_string)
First line first.
Second line second.

You can even combine f-strings with techniques we learned earlier, such as triple quotes, to handle multiple lines:

multiline_string = f"""First line {first}.
Second line {second}."""
print(multiline_string)
First line First.
Second line Second.

This is all awesome, but the real power with f-strings comes from the format. We can use f-strings to do all sorts of formatting!

import datetime
dt = datetime.datetime.now() #What time is it?
print(f'This is the datetime: {dt: %Y/%m/%d %H:%M}')
This is the datetime: 2021/08/18 10:45

When using f-strings the content following : is used to specify the format. For numbers, you can specify the number of decimals:

my_float = 444.44445
print(f'My float: {my_float:.3f}')
My float: 444.444

Or if you wanted to add leading zeros:

my_float = 444.44445
print(f'My float: {my_float:010.3f}')
My float 000444.444

Note that in this case the first 0 means "zero pad", and the following 10 represents the total width of the result. In this case it means zero pad until the full number takes up 10 characters (including the decimal place).

For floats specifically it can be helpful to think of the f-string format as f'{value:{width}.{precision}}. An overview of f-strings is included in the Resources section at the bottom of the page.

This can be helpful is you have several numbers that you want to have the same format:

print(f'First value: {555.55:7.02f}')
print(f'Second value: {22:7.02f}')
print(f'Third value: {1234.5:7.02f}')
First value: 555.55
Second value: 22.00
Third value: 1234.50

It should be noted that in the float example Python will remove digits after the . as specified by the formatting, but it won’t remove digits prior to the . using the standard f-string format:

print(f'This will be shorter: {1234.5678:7.2f}')
print(f'This will not: {123456789.00:7.2f}')
This will be shorter: 1234.56
This will not: 123456789.00

Resources