Strings II

Formatting numeric values with f-strings

In this lesson, you will learn how you can format numeric values with f-strings.


Consider the following example:

result = 10000 / 3 print(result)
Python
Output

The printed value is very difficult to read.

It would be much better if we could specify, for example, how many decimal places we want to display.

Luckily, you can use f-strings to format numerical values.

Let's first use an f-string to display the result value:

result = 10000 / 3 print(f'{result}')
Python
Output

So far, nothing changed.

Here's how you can format the result variable to display only two decimal places:

result = 10000 / 3 print(f'{result:.2f}')
Python
Output

This is much easier to read. But what exactly happens here?

What's new is the colon : followed by .2f.

.2f is a so called format specifier.

It reads as: "format the input value as a floating-point number with two decimal places".

The format specifier can vary. Whenever you add a format specifier, you need to add a colon : between the embedded value and the specifier.

We can also add a thousand separator by adding a comma after the colon:

result = 10000 / 3 print(f'{result:,.2f}')
Python
Output

Instead of 2 decimal places, we could display 4 decimal places:

result = 10000 / 3 print(f'{result:,.4f}')
Python
Output

Another formatting option is to specify a minimum width for the embedded value.

This ensures that the value occupies at least the specified number of characters, which can help in aligning and organizing your output neatly.

Here, we specify that the embedded value should have a width of at least 20 characters.

result = 10 / 5 print(f'START{result:20}END')
Python
Output

As you can see, any space not occupied by the embedded value is filled with whitespace, and the value is right-aligned.

You can also specify the alignment with > (right-aligned), < (left-aligned), and ^ (centered):

result = 10 / 5 # left-aligned print(f'{result:<20}') # right-aligned (default) print(f'{result:>20}') # centered print(f'{result:^20}')
Python
Output

There are many more formatting options that we cannot all cover in this tutorial. You can read more about them here in the official Python documentation.


What will be the output?

result = 10 / 3 print('{result:.2f}')
Python

What will be the output?

result = 10 / 3 print(f'{result:.2f}')
Python

What will be the output?

print(f'{10000/3:,.3f}')
Python