Python String Formatting

In the last lesson, we learned about Python String Slicing. Now let’s build clear text by inserting and formatting values.

Let’s Talk About Making Strings Look Good

We have some values. Maybe a name, an age, a price. And we want to put them into a string.

We could just add them with +. But that gets messy. Especially when we have numbers that need to be converted. And when we want to control how many decimal places to show. Or add commas to big numbers.

That is what string formatting is for.

String formatting lets us create a string with placeholders. Then we fill in those placeholders with values. And we can control how those values look.

Python has three main ways to format strings. Let’s go through them.

The Old Way: % Formatting in Python

This is the oldest way. It comes from the C language. It still works, but it is not recommended for new code.

We use the % operator. Inside the string, we put placeholders like %s for strings, %d for integers, %f for floats.

name = "Alex"
age = 25
print("My name is %s and I am %d years old." % (name, age))

Output

My name is Alex and I am 25 years old.

The %s gets replaced by the string. The %d gets replaced by the integer.

We can also format floats with a specific number of decimal places.

price = 19.99
print("Price: $%.2f" % price)

Output

Price: $19.99

The %.2f means a float with 2 decimal places.

But this style is old. It can get confusing when we have many placeholders. And it is easy to make mistakes with the order. So most people have moved on.

The .format() Method in Python

This was introduced in Python 2.6 and 3.0. It is more powerful and more readable than %.

We use curly braces {} as placeholders. Then we call .format() on the string and pass the values.

name = "Alex"
age = 25
print("My name is {} and I am {} years old.".format(name, age))

Output

My name is Alex and I am 25 years old.

The values are inserted in order. We can also use indices to specify which value goes where.

print("My name is {0} and I am {1} years old.".format(name, age))

Same output. But now we can reuse values.

print("{0} is {1} years old. {0} likes Python.".format(name, age))

Output

Alex is 25 years old. Alex likes Python.

We can also use named placeholders.

print("My name is {name} and I am {age} years old.".format(name="Alex", age=25))

That is more readable. And order does not matter.

We can format numbers too.

price = 19.99
print("Price: ${:.2f}".format(price))

Output

Price: $19.99

That is the .format() method. It is still used in some older code. But it is also being replaced by f-strings.

The Modern Way: f-strings in Python

f-strings were introduced in Python 3.6. They are the best way to format strings today.

We put an f before the string. And we put variables directly inside curly braces.

name = "Alex"
age = 25
print(f"My name is {name} and I am {age} years old.")

Output

My name is Alex and I am 25 years old.

That is much cleaner. No need for .format(). No need for %. Just put the variables inside the braces.

We already covered f-strings in detail in an earlier article. So I will not repeat everything. But just know that f-strings are the recommended way.

We can do formatting inside f-strings too.

price = 19.99
print(f"Price: ${price:.2f}")

Output

Price: $19.99

And we can add commas to big numbers.

population = 8000000000
print(f"World population: {population:,}")

Output

World population: 8,000,000,000

That is why f-strings are so popular. They are easy to read and easy to write.

Which One Should We Use?

Let’s use f-strings. They are the modern standard. They are fast, readable, and powerful.

If we are working with old code that uses % or .format(), we should understand them. But for new code, let’s use f-strings.

Python String Formatting: A Real-Life Example

Let’s say we are building a receipt.

item = "Coffee"
price = 4.5
quantity = 3
total = price * quantity
print(f"{'Item':<10} {'Price':>8} {'Qty':>5} {'Total':>10}")
print("-" * 35)
print(f"{item:<10} ${price:>7.2f} {quantity:>5} ${total:>9.2f}")

Output

Item Price Qty Total
-----------------------------------
Coffee $ 4.50 3 $ 13.50

That uses f-strings with alignment and number formatting. It looks like a real receipt.

Common Mistakes with Python String Formatting

Mistake 1: Forgetting the f

name = "Alex"
print("{name}") # prints {name}

So what do we do? We add the f.

print(f"{name}")

Mistake 2: Using the Wrong Format Specifier

price = 19.99
print(f"Price: ${price:.2d}") # Error!

d is for integers. For floats, we use f.

So what do we do? We use the right specifier.

print(f"Price: ${price:.2f}")

Mistake 3: Mixing % and .format()

print("Hello, %s".format("Alex")) # This doesn't work

So what do we do? We use one style consistently.

print("Hello, %s" % "Alex")

Or:

print("Hello, {}".format("Alex"))

Or:

print(f"Hello, {'Alex'}")

Mistake 4: Too Many Decimal Places

pi = 3.1415926535
print(f"Pi: {pi:.10f}")

That might be more than we need. Let’s use a reasonable number like 2 or 3.

Next, we will learn about Python String Searching and find text inside a string.