DEV Community

Cover image for Python f-Strings Explained: Format Text the Easy Way
Lavkush Kumar
Lavkush Kumar

Posted on Originally published at codingcush.com

Python f-Strings Explained: Format Text the Easy Way

Originally published on CodingCush.

An f-string is the easiest way to put variables inside text in Python: write the letter f before the string, then place any variable or expression inside curly braces, like f"Hello, {name}", and Python replaces the braces with the real value. That is the whole idea, and once you use it, the older, messier ways of joining text will feel like hard work.

The Problem: Joining Text With Plus Signs Is Messy

Every beginner starts the same way. You have a name and an age stored in variables, and you want to print one friendly sentence. So you join the pieces together with plus signs:

name = "Priya"
age = 21
message = "Hello, my name is " + name + " and I am " + str(age) + " years old."
print(message)
Enter fullscreen mode Exit fullscreen mode

This works, but it is hard to read and easy to break. Forget a space and your words stick together. Forget str() around the age and Python throws an error, because you cannot join a number to text directly.

F-strings fix this by letting the value sit inside the sentence, exactly where it belongs.

What Is an f-String, Exactly?

An f-string is a normal string with two small differences. First, the letter f goes right before the opening quote. Second, inside the string you can write curly braces, and inside those braces you put a variable or expression. Python works out the value and places it into the text for you.

name = "Priya"
age = 21
message = f"Hello, my name is {name} and I am {age} years old."
print(message)
# Hello, my name is Priya and I am 21 years old.
Enter fullscreen mode Exit fullscreen mode

The f-string reads like the final sentence. There are no plus signs and no str() conversions. The f stands for formatted, and you can use single, double, or triple quotes. If you forget the f, Python prints the braces literally, as we will see later.

F-strings arrived in Python 3.6, so they work in every modern version. You will find them everywhere, including when functions return friendly messages, which connects with how Python function arguments work in practice when you pass values in and format what comes back.

Expressions Inside the Braces

Here is the part that makes f-strings genuinely powerful: the braces do not only hold variable names. They can hold any valid expression, and Python evaluates it on the spot.

price = 250
quantity = 4
print(f"Total cost: {price * quantity} rupees")

name = "lavkush"
print(f"Shouting: {name.upper()}")

marks = [80, 90, 70]
print(f"You have {len(marks)} subjects and scored {sum(marks)} in total.")
Enter fullscreen mode Exit fullscreen mode

Calculations, method calls like upper(), and function calls like len() all work inside the braces, so you do not need temporary variables before every print.

Keep expressions short, though. If a calculation is complicated, work it out on the line above, give it a clear name, and place that name in the f-string. Short expressions inside, big logic outside.

The Input and output page of the official Python tutorial on docs.python.org showing an f-string example

The official Python tutorial's "Input and output" page (docs.python.org) — its first formatting example is an f-string.

Formatting Numbers Without Pain

Raw numbers are rarely what you want to show a user. Prices need two decimal places, big numbers need commas, and scores often look best as percentages. F-strings handle all of this with a format spec, which you write after a colon inside the braces.

amount = 499.5
print(f"Price: {amount:.2f}")        # Price: 499.50

population = 1400000000
print(f"Population: {population:,}")  # Population: 1,400,000,000

score = 0.875
print(f"Score: {score:.1%}")          # Score: 87.5%
Enter fullscreen mode Exit fullscreen mode

The pattern is value, colon, then the instruction. The code .2f means two digits after the decimal point. A comma adds thousand separators. The percent style multiplies by 100 and adds the percent sign for you.

These specs cover most real needs. The full list is in the format specification guide in the Python string documentation, worth browsing once so you know what exists. You will also see these examples with lists, so if lists are new, this guide to Python list methods with examples will help you practise formatting real list data.

Alignment and Padding for Neat Output

When you print a bill, marksheet, or simple report in the terminal, f-strings can pad values and align them left, right, or in the centre so columns line up.

print(f"{'Item':<12}{'Price':>8}")
print(f"{'Notebook':<12}{120:>8}")
print(f"{'Pen':<12}{25:>8}")

# Item           Price
# Notebook         120
# Pen               25
Enter fullscreen mode Exit fullscreen mode

Inside the spec, the number is the total width and the arrow shows direction: less than aligns left, greater than aligns right, and the caret centres. You can also pad with another character, for example f"{name:=^20}" centres a name with equals signs around it.

The official tutorial introduces f-strings right alongside these formatting ideas in the Input and output section of the Python tutorial, and working through its short examples is excellent practice.

f-Strings vs .format() vs % Formatting

You will meet three styles in code. The percent style is the oldest, from C. The format() method came next. F-strings are the newest and, for everyday work, the clearest.

Feature f-string .format() % formatting
Example f"Hello, {name}" "Hello, {}".format(name) "Hello, %s" % name
Available from Python 3.6 Python 2.6 and 3.0 Very old Python
Readability Excellent, values sit in place Good, but values are separate Poor for long text
Expressions inside Yes, directly in braces No, pass values in only No
Speed Fastest of the three Slower than f-strings Slower than f-strings
Best use today Almost everything Templates stored and reused Reading old code only

Write f-strings in new code, learn to read format() because older projects still use it, and do not start new work with percent formatting.

Common Mistakes and One Handy Tip

The first classic mistake is forgetting the f. Without it, "Hello, {name}" prints the braces literally, and beginners often stare at the output wondering what went wrong. If you ever see curly braces in your printed text, that is almost certainly the cause.

The second mistake is mixing quotes carelessly. If the string uses double quotes outside, use single quotes inside, like f"{user['name']}". Keeping quotes different is a safe habit that works everywhere.

The third mistake is using a backslash inside the braces in older versions, which was not allowed before Python 3.12. Work it out in a variable first if needed.

Now the handy tip. Add an equals sign after a variable name inside the braces and Python prints both the name and the value, which is perfect for quick debugging:

total = 999
print(f"{total=}")
# total=999
Enter fullscreen mode Exit fullscreen mode

This saves you typing the label yourself. When formatted output goes wrong in a larger program, wrapping risky code properly matters too, as shown in Python error handling with try, except and finally, so a bad value shows a clear message instead of a crash.

Frequently Asked Questions

Which Python versions support f-strings?

F-strings work from Python 3.6 onwards. Every current version supports them fully, so unless you are maintaining very old code, you can use them without worry.

Can I put a function call inside an f-string?

Yes. Any valid expression works inside the braces, including function calls, method calls, and simple calculations. Just keep long or complicated logic outside the string for readability.

How do I show two decimal places in an f-string?

Add a colon and .2f after the value, like f"{price:.2f}". The f means fixed point, and the 2 sets the number of digits after the decimal point.

Are f-strings faster than .format()?

Yes, in most cases f-strings are a little faster because Python builds them directly at compile time. The bigger win is readability, but the speed is a nice bonus.

Conclusion

F-strings are one of those rare features that are both simpler and more powerful than what came before. Put an f in front, place your values in curly braces, add a small format spec when numbers need shaping, and your text reads exactly like the final output. Practise with a bill, a marksheet, and a few debug prints today, and within a week you will not want to format text any other way.

Top comments (0)