Skip to main content

Python String Formatting

Python 3.6 gave us the f-string, which is now the favoured way to format text.

In earlier versions, the format() method filled that role.


F-Strings

An f-string lets you control how chosen parts of a string are formatted.

All it takes is an f written just before the string literal:

Example

A first, very simple f-string:

Prompt
Write a Python program that creates an f-string. Create a simple f-string with text "The price is 49 dollars" and print it.
Output: complete Python program

Placeholders and Modifiers

Values get into an f-string through placeholders, written as {}. A placeholder can hold variables, operations and functions.

It can also carry a modifier, which decides how the value looks.

Write a modifier after a colon :, using a valid formatting type. For example, .2f asks for a fixed-point number showing 2 decimal places:

Example

Drop the price variable into a placeholder:

Prompt
Write a Python program using f-string placeholders. Create a price variable set to 59 and display it in an f-string.
Output: complete Python program

Example

Show the same price with 2 decimal places:

Prompt
Write a Python program using f-string with .2f modifier. Display the price 59 with 2 decimal places.
Output: complete Python program

Placeholders and Modifiers

The value doesn't have to live in a variable. You can format it right in the placeholder:

Example

Format the number 95 with 2 decimal places:

Prompt
Write a Python program that formats a value directly in an f-string. Display the value 95 with 2 decimals without using a variable.
Output: complete Python program

Perform Operations in F-Strings

Placeholders can also run Python operations. That covers plain math, math on variables, and even if...else statements, as the next three examples show:

Example

Multiply two numbers inside the placeholder and show the answer:

Prompt
Write a Python program that performs a math operation inside an f-string placeholder. Multiply 20 * 59 directly in the placeholder.
Output: complete Python program

Example

Work out the price with tax included, right in the placeholder:

Prompt
Write a Python program that adds taxes in an f-string. Set price to 59, tax to 0.25, and display price with tax added.
Output: complete Python program

Example

Show "Expensive" when the price is above 50, and "Cheap" in any other case:

Prompt
Write a Python program with an if/else inside an f-string. Set price to 49 and display "Expensive" if over 50, else "Cheap".
Output: complete Python program

Execute Functions in F-Strings

A placeholder can call functions as well. Python's built-in methods work, and so do functions you write yourself:

Example

Call the string method upper() to turn the value into capital letters:

Prompt
Write a Python program that executes a function inside an f-string. Use the upper() method on "apples" inside an f-string.
Output: complete Python program

Example

Write your own function that turns feet into meters, then call it in the placeholder:

Prompt
Write a Python program that calls a custom function inside an f-string. Create a function that converts feet to meters and use it in an f-string.
Output: complete Python program

More Modifiers

Earlier in this lesson, the .2f modifier turned a number into a fixed-point value with 2 decimal places.

That is just one option, and other modifiers format values in different ways.

Example

Add a comma to separate the thousands:

Prompt
Write a Python program that uses a comma as a thousand separator in an f-string. Set price to 59000 and format it with commas.
Output: complete Python program

String format()

Before Python 3.6, formatting a string meant calling the format() method.

That method still works, although f-strings run faster and are the recommended choice.

The remaining examples on this page use format() so you can see how it works.

It also marks placeholders with curly brackets {}, but its syntax differs a little:

To control how a value is converted, add parameters between the curly brackets:

Example

Put a placeholder at the spot where the price should appear:

Prompt
Write a Python program using the format() method. Set price to 49 and use format() to insert it into a string.
Output: complete Python program
main.py
txt = "The price is {:.2f} dollars"

Multiple Values

Need more values? Pass them all to format():

Then give each one its own placeholder:

Example

Prompt
Write a Python program using format() with multiple values. Format quantity, item number, and price into a single string.
Output: complete Python program

Index Numbers

A number inside the curly brackets, such as {0}, is an index. It guarantees that each value lands in the right placeholder:

It also lets you use one value several times, simply by repeating its index:

Example

Prompt
Write a Python program using format() with index numbers. Use {0}, {1}, {2} to place values in the correct positions.
Output: complete Python program

Example

Prompt
Write a Python program using format() with repeated index references. Refer to the same value more than once using index numbers.
Output: complete Python program

Named Indexes

Placeholders can have names as well. Write a name between the curly brackets, as in {carname}, and then supply the value under that same name when you call the method, as in txt.format(carname = "Ford"):

Example

Prompt
Write a Python program using format() with named indexes. Use named parameters like carname and model in format().
Output: complete Python program