Introduction

f-strings are a powerful and efficient way to format output in Python. f-strings are an enhancement to string formatting that allow you to embed expressions inside string literals, using syntax that is both concise and intuitive. In this tutorial, we'll cover the basics of f-strings and how to use them to format output in Python. By the end of this tutorial, you'll have a solid understanding of how to use f-strings to format data in a clear and concise manner. Let's get started!

Table of Contents :

  • What are f-strings in Python
    • Embedding variables within f-strings
    • Embedding expressions within f-strings
    • Embedding function calls within f-strings
    • Multi-line f-strings
    • Embedding braces within f-strings

 

What are f-strings in Python

  • f-strings were introduced in Python 3.6
  • f-strings is a mechanism of formatting strings in Python.
  • f-Strings mechanism is also known as Literal String Interpolation.
  • f-strings are created by by prefixing the string literal by letter "f".
  • f-strings is a mechanism of embedding python expressions within the string literals.
  • Though f-strings cannot include comments using # symbol.
  • f-strings are faster than other two formatting mechanisms - modulo formatting and str.format()
  • f-strings are evaluated at run-time.

Embedding variables within f-strings :

  • We can embed python variables within f-strings by enclosing them within braces.
  • Code Sample :

# Embedding variables within f-strings
x = 10
my_str = f"The value of x = {x}"
print(my_str)

# Output
# The value of x = 10


Embedding expressions within f-strings :

  • We can put any valid Python expression in a f-string. 
  • Code Sample :

# Embedding expressions within f-strings
x = 10
y = 20
my_str = f"The sum of {x} and {y} = {x + y}"
print(my_str)

# Output
# The sum of 10 and 20 = 30


Embedding function calls within f-strings :


def avrg(a, b):
	return (a + b ) / 2


x = 10
y = 20
my_str = f"The average of {x} and {y} = { avrg(x, y) }"
print(my_str)

# Output
# The average of 10 and 20 = 15.0


Multi-line f-strings :

  • We can have multi-line f-strings as well.
  • We can use single, double and triple quotes in f-strings.
  • Code Sample :

def avrg(a, b):
	return (a + b ) / 2
	

x = 10
y = 20

# Multiline f-string
my_str = f'''The sum of {x} and {y} = { x + y }
The average of {x} and {y} = { avrg(x, y) }'''

print(my_str)

# Output
# The sum of 10 and 20 = 30. 
# The average of 10 and 20 = 15.0


Embedding braces within f-strings :

  • If we want braces to appear in the output, we need to use double braces in the f-string.
  • Code Samples : 

# Displaying braces in the f-strings
name = "World"
f_str = f"Embracing the :  {{ {name} }} "
print(f_str)

# Output
# Embracing the :  { World } 

Prev. Tutorial : Output formatting in Python

Next Tutorial : Using modulo operator