How to perform arithmetic operations using a formatted string

Overview

In this Answer, we will be looking at how to perform arithmetic operations using a formatted string in Python. A formatted string is a type of string that is prefixed with an f and curly braces {} to dynamically insert values into our strings.

To understand more about formatted strings in Python, go to this Answer.

Code

In the code example below, we will create numeric variables and then perform arithmetic operations such as addition, multiplication, division, and subtraction using those variables inside a formatted string.

# code to illustrate how to perform arithmetic operations in a formatted string
# defining variables
a = 6
b = 2
# creating formatted strings
print(f"a added to b gives {a+b}")
print(f"\nb sutracted from a gives {a-b}")
print(f"\na Multiplied by b gives {a*b}")
print(f"\na divided by b gives {a//b}")

Explanation

  • Line 4: We create variable a.
  • Line 5: We create variable b.
  • Lines 8–11: We perform different arithmetic operations using the formatted string.

Free Resources