Facebook Pixel

f-Strings

In Python, f-Strings are used for string formatting. Introduced in Python 3.6, they allow you to embed variables and expressions directly inside a string using curly braces {}.

To create an f-string, prefix your string with the letter f or F.

Example:

name = "Tony"
age = 35
print(f"My name is {name} and I am {age} years old.")

Output:

My name is Tony and I am 35 years old.

As seen above, the variables name and age are automatically converted into strings and inserted inside the placeholders.

Why use f-Strings?

Before f-Strings, string concatenation or the format() method was used to combine strings and variables. f-Strings make this process simpler and more readable.

Example 1: Using concatenation

name = "Tony"
age = 35
print("My name is " + name + " and I am " + str(age) + " years old.")

Output:

My name is Tony and I am 35 years old.

Example 2: Using format()

name = "Tony"
age = 35
print("My name is {} and I am {} years old.".format(name, age))

Output:

My name is Tony and I am 35 years old.

Example 3: Using f-String

name = "Tony"
age = 35
print(f"My name is {name} and I am {age} years old.")

Output:

My name is Tony and I am 35 years old.

Using Expressions inside f-Strings

You can perform operations, call functions, or use expressions directly inside the curly braces {}.

Example:

price = 50
quantity = 3
print(f"Total cost: {price * quantity} USD")

Output:

Total cost: 150 USD

Formatting Numbers

f-Strings also support number formatting such as rounding decimals or adding commas for large numbers.

Example 1: Limiting decimal places

pi = 3.1415926535
print(f"Value of pi: {pi:.2f}")

Output:

Value of pi: 3.14

Example 2: Adding commas for large numbers

num = 1000000
print(f"Number: {num:,}")

Output:

Number: 1,000,000

Formatting Dates using f-Strings

f-Strings can also be used to format date and time values easily.

Example:

from datetime import datetime
today = datetime.now()
print(f"Today is {today:%A, %B %d, %Y}")

Output:

Today is Saturday, November 08, 2025

Debugging with f-Strings

From Python 3.8 onwards, you can use = inside f-Strings to print both the variable name and its value, which is helpful while debugging.

Example:

x = 10
y = 5
print(f"{x=} and {y=}")

Output:

x=10 and y=5

Example:

name = "Steve"
marks = 91.657
print(f"Hello {name}, your score is {marks:.1f}%.")

Output:

Hello Steve, your score is 91.7%.