Formatting String with Python F-string

Starting in Python 3.6, PEP 498 introduced a new string formatting mechanism - Literal String Interpolation (known as f-string). The main idea behind f-strings is to provide a concise and convenient way to embed Python expressions in string literals for formatting. To create an f-string, add the letter "f" or "F" before the opening quotes of your string. To print the variable value in the formatted string, you must specify the variable name inside a curly brace "{}". At runtime, all variable names will be replaced by their values. In this Python F-String example, we are formatting a string using several variables. Click Execute to run Python F-String Example online and see the result.
Formatting String with Python F-string Execute
ver = 3.6

print(f"F-strings were introduced in Python {ver}.")
Updated: Viewed: 5997 times

What is a string in Python?

A Python string string is an array of 16-bit Unicode bytes (and 8-bit ANSI bytes for Python 2), where each string character is represented by one byte. One character in Python is also a string of length 1. To access the characters in the string, use the square brackets "[]". A Python string is immutable, meaning that it cannot be changed once it is created. All string processing operations return a copy of the original string and do not modify it. A literal string can be enclosed in single, double, or triple quotes. The built-in Python "str" library supplies essential methods out of the box for searching, concatenating, reversing, splitting, comparing strings, and more.

What is Python f-string?

Python f-string is the new Python syntax for string formatting, available since Python 3.6. By using Python f-strings, you can format strings in a way that is faster, more readable, and less error-prone. In Python source code, the f-string is a literal string prefixed with "f" or "F" containing expressions inside "{}" brackets.

Python f-string Syntax
a = "World"

print (f"Hello, {a}!")

# Hello, World!

Python f-string Examples

Python f-strings are very flexible and powerful. You can learn more about f-strings on the officia PEP 498 website. Following are a few examples of using f-string in Python with short descriptions:

How to format numbers using f-strings?

In Python, f-strings support a "mini-format specification language" that gives us advanced formatting options for numbers. Below is an example formatting numbers using Python f-strings:

Formatting Numbers using f-strings Example
from math import pi

print(f"The value of Pi: {pi:.2f}")
          
# The value of Pi: 3.14

How to format date or time using f-strings?

You can format dates and times with f-strings in Python. Below is an example of printing the current date and time using Python f-strings:

Formatting Date or Time using f-strings Example
from datetime import datetime as dt
  
now = dt.now()
  
print(f"Current time {now:%d.%m.%Y %H:%M}")
  
# Current time 29.12.2021 01:11

How to make arithmetic operations using an f-string?

F-strings can be used to perform math operations. The following is an example of performing arithmetic operations on Python f-strings:

Arithmetic Operations using f-string Example
x = 20
y = 10
          
print(f"{x} x {y} / 2 = {x * y / 2}")
          
# 20 x 10 / 2 = 100.0

How to get list values by index using f-strings?

Python f-strings can read element values from lists and dictionaries. The following is an example of accessing a list element by its index.

Get List Values using f-string Example
planets = ["Mercury", "Venus", "Earth", "Mars"]

print(f"We live on the {planets[2]}")
      
# We live on the Earth

How to access elements by object key using f-strings?

Using f-strings, you can access dictionary elements by a key:

Get Element by Object Key using f-strings Example
planet = {"name": "Earth", "radius": 6378000}

print(f"Planet {planet['name']}. Radius {planet['radius']/1000} km.")

# Planet Earth. Radius 6378.0 km.

How to use complex objects in f-string?

Python f-strings can call object methods:

Complex Objects using f-string Example
name = "Jack"

print(f"Name: {name.upper()}")

# Name: JACK

How to call a function in f-strings?

Python f-strings can call global functions:

Call a Function using f-stringExample
print(f"10 / 2 = {round(10/2)}")

# 10 / 2 = 5

See also