Even this Python knows how to format strings the right way!
Format Strings in Python: Let me show you something really useful in Python—string formatting.
When you’re working with Python, you’ll often need to print messages to the screen. Maybe you’re showing a user’s name, printing a calculation, or just making your program’s output look clean and clear.
To do all that properly, you need to understand how Python string formatting works—especially using the print() function and the format() method.
Now, don’t worry if this sounds technical. I’m going to walk you through it step by step. We’ll start with the basics and build up from there.
By the end of this guide, you’ll know:
print() in Python to show messages with variables.format() method helps you insert values into strings.This isn’t just a list of examples—it’s a hands-on way to learn Python string formatting, so you can understand why it works the way it does.
So open up your Python editor, and let’s start learning how to make your output look clean, professional, and easy to read.
print() Function in Python?The print() function in Python is one of the very first things you’ll learn when writing code. It’s used to display messages or results in the console. Whenever you want your program to show something to the user, you use a print statement.
print()?The main purpose of the print() function is to output information. This can be:
"Hello, World!"So any time you want your program to “speak,” print() is how you do it.
Here’s the most basic way to use print():
print("Hello, World!")
When you run this, Python will display:
Hello, World!
This is a classic example. It’s simple, but it shows the core idea of the print statement: sending output to the screen.
You’ll use print() all the time—for testing, debugging, or just showing results. As you go further, you’ll also learn how to use print() for formatted output, which means making the printed text look nice, organized, and clear.
And that’s exactly what we’ll start working on next—how to make your output more meaningful using formatting.
format(): The Key to Python String FormattingNow that you’re comfortable with the print() function, let’s take it a step further. One of the best ways to make your output cleaner and more dynamic is by using the format() function in Python.
This is where string formatting becomes really useful—especially when you want to include variables in your messages.
format() Works in PythonThe format() method lets you insert values directly into a string by using placeholders. A placeholder is just a pair of curly braces {} inside your string. Wherever you put {}, Python will fill it with a value you provide using .format().
Let me show you a simple example:
name = "Alex"
print("Hello, {}".format(name))
Here’s what’s happening:
"Hello, {}" is the string template, and {} is the placeholder..format(name) tells Python to insert the value of name into the {}.Hello, Alex
This technique is called string interpolation, because you’re inserting (or interpolating) values into a string.
Using the Python format function makes it easy to:
+It works with more than one value, too! We’ll explore that shortly.
When you’re formatting strings in Python, you’re not limited to just one value. You can insert multiple values into a single string using more than one placeholder.
Here’s a simple example with two values:
print("Name: {}, Age: {}".format("Alice", 30))
What’s happening here?
{} and {} are placeholders for values..format("Alice", 30) sends "Alice" to the first {} and 30 to the second {}.Name: Alice, Age: 30
This is clean, readable, and way easier than trying to join strings manually.
You can also control the order of the values by using index-based placeholders. Here’s how:
print("{1}, {0}".format("first", "second"))
Let’s break this down:
{1} refers to the second item in .format(), which is "second".{0} refers to the first item, "first".So the output will be:
second, first
This is helpful when you want to reuse values or arrange them differently in your output.
Using multiple placeholders and index-based formatting gives you more control over how your output looks. And don’t worry—we’ll soon explore named placeholders and more advanced tricks too.
format()Instead of using {} or index numbers like {0}, you can use named placeholders inside your string. This means you label each placeholder with a name, and then pass values using keyword arguments inside the format() function.
print("Name: {name}, Age: {age}".format(name="Bob", age=25))
Let’s break it down:
{name} and {age} are named placeholders..format(), you pass values using name="Bob" and age=25.The output will be:
Name: Bob, Age: 25
Example with reuse:
print("{name} is {age} years old. {name} loves Python.".format(name="Bob", age=25))
Output:
Bob is 25 years old. Bob loves Python.
Named placeholders are a big help when your output gets more detailed. Want to learn how to format numbers (like decimal places or padding)? We can jump into that next if you’re ready!
Sometimes, you don’t just want to print a value—you want to format it nicely. Maybe you want to round a number, control how many decimal places show, or align values for cleaner output.
That’s where format specifiers come in.
Let’s say you have a float value like Pi, and you want to show only 2 decimal places. Here’s how you do it:
value = 3.14159
print("Pi is approximately {:.2f}".format(value))
Explanation:
:.2f is a format specifier.: tells Python you’re starting a format instruction..2f means “2 digits after the decimal point” as a float.Output:
Pi is approximately 3.14
Here are a few you’ll use often:
| Specifier | Meaning |
|---|---|
:d | Format as an integer (whole number) |
:f | Format as a float |
:.2f | Float with 2 decimal places |
:> | Right-align the text |
:< | Left-align the text |
:^ | Center-align the text |
print("{:<10} | {:^10} | {:>10}".format("Left", "Center", "Right"))
Output:
Left | Center | Right
Each column is 10 characters wide:
< makes it left-aligned,^ centers the text,> makes it right-aligned.This is super useful when you’re printing tables or reports and want everything to line up neatly.
Let’s say you’re building a small program to display product details: name, quantity, price, and total cost. We’ll use everything you’ve learned to format it neatly.
print("{:<10} {:>10} {:>10} {:>12}".format("Item", "Qty", "Price", "Total"))
print("-" * 44)
item1 = "Apple"
qty1 = 5
price1 = 0.99
total1 = qty1 * price1
item2 = "Banana"
qty2 = 12
price2 = 0.35
total2 = qty2 * price2
print("{:<10} {:>10} {:>10.2f} {:>12.2f}".format(item1, qty1, price1, total1))
print("{:<10} {:>10} {:>10.2f} {:>12.2f}".format(item2, qty2, price2, total2))
Output:
Item Qty Price Total
--------------------------------------------
Apple 5 0.99 4.95
Banana 12 0.35 4.20
:<10 → Left-align the item name in a 10-character space.:>10 → Right-align quantity and price in 10 characters.:>10.2f → Right-align and format float with 2 decimal places.:>12.2f → Wider column for total, 2 decimal places."-" * 44 → A simple line to separate the header and the data.This gives you a clean layout that looks almost like a printed receipt.
Starting from Python 3.6, you can use f-strings (formatted string literals). Instead of calling .format(), you just add an f before the string and write your variables directly inside {}.
name = "Alice"
age = 30
print(f"Name: {name}, Age: {age}")
Output:
Name: Alice, Age: 30
No need for .format()—just use the variables straight inside the curly braces. Much cleaner, right?
You can use the same format specifiers with f-strings as you did with format().
pi = 3.14159265
print(f"Pi rounded to 2 decimal places: {pi:.2f}")
Output:
Pi rounded to 2 decimal places: 3.14
Same result, but less typing.
Let’s recreate part of the table example using f-strings:
item = "Orange"
qty = 3
price = 1.25
total = qty * price
print(f"{'Item':<10} {'Qty':>5} {'Price':>10} {'Total':>10}")
print("-" * 40)
print(f"{item:<10} {qty:>5} {price:>10.2f} {total:>10.2f}")
Output:
Item Qty Price Total
----------------------------------------
Orange 3 1.25 3.75
.2f, :>10, :<15, etc..2f, :>10, :<15, etc.Now let’s take your formatting skills a step further by using format() inside loops. This is especially useful when you’re working with dynamic output, like creating logs, showing results, or printing data reports.
format() in Loops and Dynamic OutputWhen you’re looping through data, format() lets you insert values directly into strings for clean, readable output—even when the content changes every time.
for i in range(5):
print("Index: {}, Square: {}".format(i, i * i))
Output:
Index: 0, Square: 0
Index: 1, Square: 1
Index: 2, Square: 4
Index: 3, Square: 9
Index: 4, Square: 16
for i in range(1, 6):
print("Index: {:>2}, Square: {:>3}".format(i, i * i))
Output:
Index: 1, Square: 1
Index: 2, Square: 4
Index: 3, Square: 9
Index: 4, Square: 16
Index: 5, Square: 25
This uses :>2 and :>3 to right-align the numbers in consistent-width columns, which makes the output much easier to read—especially when you have larger values.
Let’s take that same loop example and upgrade it using f-strings. This is the cleaner and more modern way to handle dynamic output in loops, and it works just as well—if not better—for logs, reports, or any data processing.
You don’t need .format() anymore—just add an f before the string and write your variables directly inside {}. You can even use format specifiers right there.
for i in range(5):
print(f"Index: {i}, Square: {i * i}")
Output:
Index: 0, Square: 0
Index: 1, Square: 1
Index: 2, Square: 4
Index: 3, Square: 9
Index: 4, Square: 16
Same result, but the code is easier to read and write.
Let’s improve readability by aligning the numbers:
for i in range(1, 6):
print(f"Index: {i:>2}, Square: {i * i:>3}")
Output:
Index: 1, Square: 1
Index: 2, Square: 4
Index: 3, Square: 9
Index: 4, Square: 16
Index: 5, Square: 25
:>2 right-aligns the index to 2 spaces.:>3 right-aligns the square to 3 spaces.:.2f, :>10, etc.).If you’re building anything that involves data rows, progress tracking, or even debugging output, f-strings in loops can really clean things up.
Let’s level up with a real-world use case: looping through a list of dictionaries—like product data, user info, or logs—and printing everything cleanly using f-strings.
Let’s say you’re working with a list of user records. Each record is a dictionary with name, email, and age.
users = [
{"name": "Alice", "email": "alice@example.com", "age": 28},
{"name": "Bob", "email": "bob@example.com", "age": 34},
{"name": "Charlie", "email": "charlie@example.com", "age": 22},
]
print(f"{'Name':<10} {'Email':<25} {'Age':>3}")
print("-" * 40)
for user in users:
print(f"{user['name']:<10} {user['email']:<25} {user['age']:>3}")
Output:
Name Email Age
----------------------------------------
Alice alice@example.com 28
Bob bob@example.com 34
Charlie charlie@example.com 22
:<10 aligns the name to the left in a 10-character column.:<25 ensures email is readable and spaced out.:>3 right-aligns the age for a clean, tabular look.Let’s simulate a simple log system where each message is printed with the current timestamp:
from datetime import datetime
events = ["User logged in", "File uploaded", "Error occurred", "User logged out"]
for event in events:
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"[{timestamp}] {event}")
Output (example):
[2025-04-09 14:32:12] User logged in
[2025-04-09 14:32:12] File uploaded
[2025-04-09 14:32:12] Error occurred
[2025-04-09 14:32:12] User logged out
You can use this to format debug logs, activity feeds, or execution reports with clarity.
print() vs .format() vs f-Strings (With Examples)| Feature | print() (basic) | .format() | f-Strings |
|---|---|---|---|
| Basic Usage | print("Name:", "Alice") | print("Name: {}".format("Alice")) | name = "Alice"print(f"Name: {name}") |
| Multiple Values | print("Name:", "Bob", "Age:", 25) | print("Name: {}, Age: {}".format("Bob", 25)) | name = "Bob"age = 25print(f"Name: {name}, Age: {age}") |
| Readability | Okay, can get messy | Harder with many placeholders | ✅ Very clean: print(f"Hello, {name}") |
| Formatting Numbers | ❌ Not built-in | value = 3.14print("Pi: {:.2f}".format(value)) | value = 3.14print(f"Pi: {value:.2f}") |
| Positional Arguments | ❌ Not supported | print("{1}, {0}".format("first", "second")) | a, b = "first", "second"print(f"{b}, {a}") |
| Named Placeholders | ❌ Not supported | print("{name}".format(name="Alex")) | name = "Alex"print(f"{name}") |
| Works in Loops | ✅ for i in range(3): print(i) | ✅ for i in range(3): print("Index: {}".format(i)) | ✅ for i in range(3): print(f"Index: {i}") |
| Alignment & Padding | ❌ Manual spacing only | print("{:<10}".format("Item")) | print(f"{'Item':<10}") |
| Speed / Performance | Fast enough for most uses | Slower than f-Strings | ✅ Fastest method (preferred in large scripts) |
| Python Version | All versions | Python 2.7+ and 3.x | ✅ Python 3.6+ only |
| Best For | Beginners, quick checks | Compatible formatting with older code | ✅ Clean scripts, logging, dynamic data |
print() and .format() — and How to Fix Them.format()If you use placeholders {} but don’t provide enough values, Python will raise an error.
# ❌ Incorrect:
print("Name: {}, Age: {}".format("Alice"))
# ❗ Error:
# IndexError: Replacement index 1 out of range for positional args tuple
Fix: Provide all required arguments.
print("Name: {}, Age: {}".format("Alice", 30))
Using {1} and {0} means you’re specifying the order manually. If you mix it up, the output becomes confusing.
# ❌ Incorrect:
print("{1}, {0}".format("first"))
# ❗ Error:
# IndexError: tuple index out of range
Fix: Make sure you provide the right number of values, in the correct order.
print("{1}, {0}".format("first", "second"))
# Output: second, first
.format()This happens when you write the string with {} but forget to use .format() at the end.
# ❌ Incorrect:
print("Hello, {}")
# Output: Hello, {}
Fix: Call .format() with the value you want to insert.
print("Hello, {}".format("Alex"))
# Output: Hello, Alex
Using f-Strings and .format() together won’t work:
# ❌ Incorrect:
name = "Sam"
print(f"Hello, {}".format(name)) # Won't work
Fix: Use one or the other, not both.
# f-String
print(f"Hello, {name}")
# OR .format()
print("Hello, {}".format(name))
print() and format()By now, you’ve seen how powerful and flexible string formatting in Python can be. From the basic print() statement to more dynamic output using the format() function, you’ve learned how to:
:.2f, :<, :^, and more.format() callYou also got a side-by-side comparison of print(), .format(), and f-Strings, so you know exactly when to use each one.
Whether you’re just starting out or brushing up your Python basics, understanding how to use print() and format() the right way helps you write cleaner, clearer, and more professional code.
💡 Found this helpful?
Do me a favor — share this post with your friends, colleagues, or on your social media. You never know who might need a quick Python refresher before their next interview.
✍️ For more Python tricks, breakdowns, and real-world coding insights, head over to emitechlogic.com. I post new tutorials regularly!
Thanks for reading
📸 Instagram: https://www.instagram.com/emi_techlogic/
💼 LinkedIn: https://www.linkedin.com/in/emmimal-alexander/
#PythonQuiz #CodingInterview #PythonInterviewQuestions #MCQChallenge #PythonMCQ #EmitechLogic #UncoveredAI #PythonTips #AIwithEmi #PythonCoding #TechWithEmi
print() and .format() in Python? The print() function in Python is used to display output on the console, while .format() is a method used to insert values into strings in a controlled way. You can use .format() inside a print() statement to create formatted output. For example:
print(“Hello, {}”.format(“Alice”))
This prints: Hello, Alice — combining both print() and .format().
format() function? You can use multiple curly braces {} to define placeholders for each value, then pass those values in order inside .format(). This is helpful when creating formatted output in Python using multiple values:
print(“Name: {}, Age: {}”.format(“Bob”, 25))
If you want to control the order, use index-based placeholders:
print(“{1}, {0}”.format(“first”, “second”)) # Output: second, first
.format() placeholder not working in the Python print statement? One of the most common Python string formatting errors is forgetting to actually call the .format() method. If you write:
print(“Hello, {}”)
You’ll just get: Hello, {}
Fix it by adding .format():
print(“Hello, {}”.format(“Alex”))
.format() or f-Strings for formatting strings in Python? If you’re using Python 3.6 or later, f-Strings are usually better than .format() because they are faster and easier to read. For example:
name = “Emma”
print(f”Hello, {name}”)
But if you’re writing code for older Python versions, the format() function is still the best choice for string interpolation in Python.
🔗 Python Official Documentation: str.format()
This is the official Python documentation with detailed syntax, format specifiers, and use cases.
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.