Mastering Python String Formatting — a visual overview of the four main methods: F-Strings, .format(), % formatting, and Template Strings.
String formatting is also known as formatted string construction. It is an operation that consists of building a string containing variable information by inserting values into a predetermined string format or design. It allows dynamic string composition without the necessity of concatenating values manually.
If you have to print a person’s name and age. You may do it like this:
name = "Alice"
age = 30
print("Name: " + name + ", Age: " + str(age))
But honestly, that looks a bit clunky.
Now look at this version:
print(f"Name: {name}, Age: {age}")
Much cleaner, right?
It’s not just for printing names and ages either. You can use it when you need to:
Python gives us a few ways to do this:
.format() method — still useful, especially when you need a bit more control.% formatting — old-school, but you’ll still run into it in older codebases.At the end of the day, string formatting is all about making your output look clean and professional — without turning your code into a mess of quotes and plus signs.
Now let’s explore F-strings
If you’re using Python 3.6 or newer, f-strings (short for formatted string literals) will probably be your favorite method of string formatting. Personally, they’re my top choice — and the reasons why are good ones: they’re quick, readable, and compact.
Let’s understand why.
An f-string is a string that starts with the character f or F, and you can insert Python expressions directly within the string with curly braces {}.
Rather than constructing strings by hand or with .format(), f-strings allow you to insert variables, function calls, or math inline — making the code much more readable and maintainable.
Here’s what makes f-strings my default choice in most projects:
You can clearly see where the variables are used — right inside the string.
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
Output:
My name is Alice and I am 30 years old.
There’s no guesswork, no juggling of positions, and no need to reference arguments by index or key. It’s exactly what you see.
Internally, f-strings are compiled at runtime, which means they’re generally faster than .format() or % formatting. When you’re formatting strings inside loops or performance-sensitive code, this matters.
You’re not limited to variables. You can run any valid Python expression inside the {}.
x = 5
y = 3
print(f"The sum of {x} and {y} is {x + y}.")
Output:
The sum of 5 and 3 is 8.
This avoids creating temporary variables just to show a value.
You can apply number formatting, alignment, padding, and more — all directly inside the f-string.
price = 1234.567
print(f"Total: ${price:,.2f}")
Output:
Total: $1,234.57
Here:
It’s concise and self-explaining.
Compare the same output using different methods:
Using .format()
"Total: ${:,.2f}".format(price)
Using f-string
f"Total: ${price:,.2f}"
The f-string version is shorter, more direct, and easier to follow.
F-strings are ideal for:
As long as you’re working with Python 3.6 or later, they are generally the optimal choice for string formatting.
Although f-strings are powerful, they do have some restrictions:
They don’t work with Python 2.x or versions prior to 3.6.
They execute expressions immediately — which is wonderful for power, but you need to be careful when working with untrusted data (e.g., in web development).
You can’t reuse a placeholder by name — you’d need to retype the same variable again if necessary multiple times.
F-strings are quick, readable, and expressive.
If you’re working with Python 3.6 or higher, they streamline your string formatting and make your code cleaner.
That’s why — for me and for many — f-strings are the first choice when dynamically constructing strings.
Now, Let’s have a look at the .format() method — how it works, when to use it, and why it can still be really useful, especially when you require structured and flexible string building.
.format() Method — A Detailed Explanation.format() Method in Python?The .format() method is a Python built-in string method that enables you to place values within a string with the use of placeholders expressed as curly braces {}.
Introduced in Python 2.7 and 3.0, it was originally designed to replace the older % formatting method and remains a widely used approach, especially in situations where:
"template string with {} placeholders".format(values)
Every {} is replaced by an argument passed to the .format() method.
msg = "Hello, {}, you have {} new messages."
result = msg.format("Alice", 3)
print(result)
Output:
Hello, Alice, you have 3 new messages.
You can also mention the position by name:
msg = "First: {0}, Second: {1}, Again First: {0}"
print(msg.format("X", "Y"))
Output:
First: X, Second: Y, Again First: X
Here, {0} and {1} are argument positions.
This is one of .format()’s strongest features:
msg = "Name: {name}, Score: {score}"
print(msg.format(name="Bob", score=95))
Output:
Name: Bob, Score: 95
price = 1234.56789
msg = "Price: {:.2f}".format(price)
print(msg)
Output:
Price: 1234.57
:.2f formats the number with 2 decimal placesprint("{:<10} | {:>5}".format("Item", 25))
Output:
Item | 25
<10 means left-align in a 10-character space>5 means right-align in a 5-character space.format()If your data is stored in a dictionary, you can unpack it into the string:
info = {"name": "Emma", "marks": 91}
msg = "Student: {name}, Marks: {marks}"
print(msg.format(**info))
Output:
Student: Emma, Marks: 91
The ** operator unpacks the dictionary into keyword arguments.
You can repeat the same variable multiple times, or reorder them:
template = "Subject: {sub}, Marks: {marks}, {sub} is your favorite."
print(template.format(sub="Math", marks=95))
Output:
Subject: Math, Marks: 95, Math is your favorite.
This is not possible with f-strings unless you store the value in a separate variable.
.format() More Useful Than f-strings?| Situation | Why .format() Helps |
|---|---|
| Older Python versions | Works in Python 2.7 and 3.x |
| Dynamic templates | Easier when your template comes from outside (like files or UI) |
| Reusing values | Lets you repeat or rearrange variables in the string |
| Dictionaries or mappings | Supports **dict unpacking into placeholders |
| Formatting without expression evaluation | Good when you want structure without runtime expression execution (e.g., internationalization systems) |
Percent formatting is an older string formatting technique that utilizes the % operator to place values inside a string. You insert the format specifiers (such as %s, %.2f, etc.) within the string, and then use % followed by a tuple of the values you would like to place inside.
Even though it’s older, this technique is still compatible in contemporary Python.
language = "Python"
version = 3.11
message = "We are learning %s version %.2f" % (language, version)
print(message)
"We are learning %s version %.2f"
This is the template string. It has two placeholders:
%s: for a string%.2f: for a floating-point number, rounded to 2 decimal placeslanguage = "Python"
version = 3.11
language is a stringversion is a float%:% (language, version)
We are learning Python version 3.11
| Format Code | Meaning | Example |
|---|---|---|
%s | String | "Python" |
%d | Integer (decimal) | 42 |
%f | Floating-point number (default 6 decimals) | 3.141593 |
%.2f | Float with 2 decimal places | 3.14 |
%x / %X | Hexadecimal | 0x1f or 0X1F |
name = "Alice"
marks = 88.6789
result = "Student: %s | Marks: %.1f" % (name, marks)
print(result)
Output:
Student: Alice | Marks: 88.7
Template strings are one method of string creation that involves variables. They are from the string module in Python. Rather than using {} like f-strings or .format(), you use a dollar sign and a variable name as follows:
from string import Template
t = Template("Hello, $name!")
print(t.substitute(name="Alice"))
Output:
Hello, Alice!
When you let users input data (e.g., completing a form or typing into a chat box), you can’t always be sure what they’ll type. If you use f-strings or .format() on that input directly, and you’re not paying attention, it could lead to issues — such as running unwanted code.
Template Strings circumvent this threat by handling all user input as plain text. They do not attempt to execute it, compute it, or interpret it as a command.
Example:
from string import Template
user_input = "__import__('os').system('rm -rf /')" # harmful input
template = Template("User typed: $text")
print(template.substitute(text=user_input))
Output:
User typed: __import__('os').system('rm -rf /')
It simply prints the text — it does not execute any commands.
Example:
from string import Template
message = Template("Welcome, $user! You have $messages new messages.")
print(message.substitute(user="Tom", messages="3"))
Output:
Welcome, Tom! You have 3 new messages.
In case you forget to supply one of the variables, substitute() will throw an error. To prevent that, use safe_substitute() — it will keep the missing variable intact.
t = Template("Hello, $name! Your score is $score")
print(t.safe_substitute(name="John"))
Output:
Hello, John! Your score is $score
If you need to display a dollar sign (say, $100), use two dollar signs $.
t = Template("Price: $$${amount}")
print(t.substitute(amount="25"))
Output:
Price: $25
Template Strings:
# string_formatting_examples.py
# Example 1: Using f-strings
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
# Example 2: Using str.format()
price = 49.99
print("The price of this item is ${:.2f}".format(price))
# Example 3: Using % operator
language = "Python"
version = 3.11
print("I am learning %s version %.1f" % (language, version))
# Example 4: Aligning text
print("{:<10} | {:^10} | {:>10}".format("Left", "Center", "Right"))
# Example 5: Padding numbers
for i in range(1, 6):
print(f"Number: {i:03}")
Python’s string formatting has come a long way since its development. Although all four approaches are acceptable, f-strings are the new, Pythonic way to do string formatting. They provide the optimal balance of readability, performance, and features.
Key takeaways:
Practice these techniques in your own projects, and you’ll soon find yourself creating beautifully formatted strings with ease!
1. What is the most recommended string formatting method in Python 3.6+?
2. When should I use the .format() method?
.format() when you need dynamic placeholder positions or are working with older versions of Python.3. Is % formatting still used?
4. Are f-strings safer than template strings?
5. Can I use expressions inside f-strings?
f"{x + y}".After debugging production systems that process millions of records daily and optimizing research pipelines that…
The landscape of Business Intelligence (BI) is undergoing a fundamental transformation, moving beyond its historical…
The convergence of artificial intelligence and robotics marks a turning point in human history. Machines…
The journey from simple perceptrons to systems that generate images and write code took 70…
In 1973, the British government asked physicist James Lighthill to review progress in artificial intelligence…
Expert systems came before neural networks. They worked by storing knowledge from human experts as…
This website uses cookies.