What Are f-strings in Python? How to Use f-strings in Python

F-strings in Python provide a very powerful way to easily format strings as per your requirement. Python websites and apps heavily rely on strings to store different kinds of data. Often you need to format strings in different ways to present information in different situations. Most often, the format of data stored in back end database is different from the way it needs to be displayed to end users. In such cases, you can f-strings in Python. In this article, we will learn what are f-strings in Python and How to use them.

What Are f-strings in Python?

Python began supporting f-strings from version 3.6. Before that, you had to use format() function. But now f-string has become the preferred way to format strings. This is mainly because it is faster than using format() function. Also , it allows you to format entire string or certain specific parts of the string, as you need. You can specify a string as f-string, by adding prefix ‘f’ just before it.

txt = f"Good morning"
print(txt) # output is Good morning

The main benefit of using f-string is that you do not need to store data along with its format, in your back end databases. You can format data on the fly before displaying it. You can even change the format as you need, without touching its storage.

How to Use f-strings in Python

Let us learn the different aspects of using f-strings in Python. Every f-string consists of two parts – placeholders and modifiers. Let us look at each of them in detail.

Placeholders

F-string placeholders are denoted by curly braces {}. Each f-string can have one or more placeholders. Each placeholder can have variables, operators and even functions. They can also contain modifiers. Here is an example of f-string with placeholder for variable age. Its value is substituted during runtime.

age = 25
txt = f"I am {age} years old"
print(txt) # output is I am 25 years old

If you also want to display the name of the variable, just add = sign after variable name in f-string.

Modifiers

Modifiers determine the format of the value. It is specified by adding a colon ‘:’, followed by format string such as .3f that means floating point number with 3 decimals.

Here is an example to display price with 2 decimal places.

price = 31
txt = f"It costs ${price:.2f}"
print(txt) # output is It costs $31.00

When you run the above code, it will substitute the placeholder for price variable, after formatting it to 2 decimal places.

You can also format these values directly without using variables.

Integers, floats, numbers and scientific notation

You can use integers or floats as it is without any format modifiers.

a=45
b=10.5
c=1.23e3
print(f"I got {a} marks") # I got 45 marks
print(f"The price is ${b}") # The price is 10.5
print(f"{c}") # 1230.0

Alternatively, for integers, you can use ‘d’ format modifier, for floats you can use ‘f’ format modifier and for scientific notation, you can use ‘e’ or ‘E’ format modifier. You can add these modified by adding a colon ‘:’ after the variable, followed by format modifier.

a=45
b=10.5
c=1.23e3
print(f"I got {a:d} marks") # I got 45 marks
print(f"The price is ${b:.2f}") # The price is $10.50
print(f"{c:e}") # 1.230000e+03

Percentages %

If you want to display percentage values in your string, you can use percentage format specifier ‘%’.

val = 0.5

print(f"I got {val:%} marks") # output is I got 50.000000% marks

In some Python environment, since we have not specified the number of decimal places, the result may contain a lot of zeroes. Therefore, you can also specify decimal precision.

val = 0.5

print(f"I got {val:.1%} marks") # output is I got 50.0% marks

When you mention percentage format modifier Python will automatically multiply the percentage value by 100 and suffix it with % sign.

Dates

If you have dates stored in proper date objects then you can either display it as it is or using format specifiers. Here is an example to display the date as it is.

from datetime import date
d = date(
year=2025,
month=4,
day=2
)

print(f"{d}") # output is 2025-04-02

You can also use format specifiers %Y for year, %m for month and %d for day, %b for short version of month as text and %B for long version of month as text. Here is an example using format specifiers for year, month and day.

print(f"{d:%Y/%m/%d}") # output is 2025/04/02

Of course there are many other date format specifiers to format date objects as per your requirement.

Mathematical Operations in f-string

Earlier, we had mentioned that you can also perform mathematical operations inside f-strings. You can do this using mathematical operators such as +,-,*, etc.

txt = f"You got {20 * 10} marks"
print(txt) # output is You got 200 marks

When Python interpreter evaluates the above f-string, it will use ‘*’ operator to multiple 20 and 10 and replace the placeholder with result 200.

You can also do mathematical operations using variables.

a=20
b=10
txt = f"You got {a * b} marks"
print(txt) # output is You got 200 marks

You can use round brackets in case of complicated operations. The expression inside the placeholder will be evaluated as per proper mathematical precedence and the placeholder will be replaced with the result of evaluation.

a=2
b=10
c=30
txt = f"You got {a * (b+c)} marks"
print(txt) # output - You got 80 marks

You can also use conditional operators such as if-else statements in the placeholder.

a=24
txt = f"This is {'expensive' if a>25 else 'inexpensive'}"
print(txt)

In the above code, Python evaluates the conditional expression and replaces placeholder with the result of expression.

Function Call in f-string

You can also make function calls inside f-string’s placeholders. Here is an example where the name variable stores name in lower case. In our f-string placeholder, we convert it into upper string using upper() function.

name = "joe"
txt = f"My name is { name.upper()}"
print(txt) # My name is JOE

Nesting

You can also use one placeholder inside another placeholder in f-string, if you want. Here is an example.

val = 2.5
precision = 2

print(f"{val:.{precision}f}") # 2.50

In the above code, we have used val variable inside the outer placeholder. Then we have used precision variable in the inner placeholder.

Conclusion

In this article, we have learnt what f-string is and how to use it in Python. We have learnt how to use variables, operators, functions and even modifiers in f-strings. We have also learnt how to use nest multiple variables in an f-string. As you can see, f-strings are very easy to use, offer tons of formatting options.

FAQ

1. What is the benefit of using f-string in Python?

You do not need to store the format of data, while saving it to your back end database. You can format the data on the fly while displaying it to your end users, on web pages or web apps.

2. How to use f-string in Python?

First, you need to prefix the string with ‘f’ so that Python interprets it as f-string. The placeholder is specified in the string using curly braces {}. The place holder can contain numbers, texts, variables, dates, operators and even function calls. Optionally, you can use a modifier to format the value of placeholder.

val=10
print(f"it is {val}'o clock")

# output
it is 10'o clock

Also read:

How to Work With Zip Files in Python
How to Convert Pandas Dataframe to Dictionary
How to Convert Pandas Dataframe to List

Leave a Reply

Your email address will not be published. Required fields are marked *