Skip to main content
Practice

How to Format Strings with f-Strings

f-strings provide a simple and readable way to insert variable values or expressions directly into strings in Python.

They are used by prefixing the string with f or F, and variables or expressions can be inserted within curly braces {}.

Example of using f-strings
name = "CodeFriends"
age = 20

greeting = f"My name is {name}, and I am {age} years old."

# "My name is CodeFriends, and I am 20 years old."
print(greeting)

In this example, the f-string is used to insert the values of the variables name and age into the string greeting.


Applying Expressions in f-Strings

Within an f-string, you can include expressions such as arithmetic operations, comparisons, and more.

An expression is a combination of variables, values, or operations that evaluates to a result.


Example of using an exponentiation expression
number = 10

result = f"The square of 10 is {number**2}."

print(result) # "The square of 10 is 100."

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.