Python String Formatting

In the last lesson you learned String Slicing. There you pulled out parts of a string by their position. Now we go the other way. Instead of taking text apart, we build new text. We drop our own values right into the middle of it.

🤔 Why String Formatting?

Picture this. You want to print a line like Alex scored 92.5 in the test. The name and the score live in variables. So how do you join plain words and your values into one clean sentence?

You could glue the pieces together with + signs. It works. But it gets ugly fast. And it breaks the moment a number sneaks in.

Here is the messy way with +:

name = "Alex"
score = 92.5
print("Name: " + name + ", Score: " + str(score))

See the problem? You have to call str() on the number. If you forget, Python throws an error. And all those quotes and plus signs are easy to get wrong.

String formatting is the clean way to put values inside a string. You write the sentence once. You mark the spots where values go. Then Python fills them in for you.

🧩 F-strings: The Modern Way

An f-string is a normal string with the letter f in front of it. Inside it, anything you put in curly braces gets replaced by its value.

Here is the same line as before, now with an f-string:

name = "Alex"
score = 92.5
print(f"Name: {name}, Score: {score}")

Output

Name: Alex, Score: 92.5

Let us read it slowly:

  • The f before the opening quote tells Python this is an f-string.
  • {name} is a placeholder. Python swaps it for the value of name.
  • {score} does the same for the score.
  • No str(). No + signs. The number just works.

You can even run small bits of code inside the braces. Python works out whatever is in there first. Then it drops the result into the text.

This example does math right inside the braces:

price = 250
quantity = 3
print(f"Total: {price * quantity}")

Output

Total: 750

So an f-string is not just for plain variables. Whatever sits in the braces gets worked out and placed into the line.

Tip

F-strings were added in Python 3.6. They are the recommended way to format strings today. They are short and easy to read.

🎯 Format Specs: Controlling How Values Look

Sometimes the raw value is not pretty enough. A price might show as 9.5 when you want 9.50. A long number might need commas. This is where format specs come in.

A format spec is a small instruction you add after a colon inside the braces. The shape is {value:spec}.

Decimal places

This is the most common one. To show a number with exactly two digits after the dot, use :.2f.

This formats a price to two decimal places:

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

Output

Price: 9.50

The .2f means “show this as a float with 2 digits after the decimal point”. Change the 2 to any number you need. :.3f gives three digits. :.0f rounds to a whole number.

Thousands separator

For big numbers, a comma makes them easier to read. Use :, for that.

This adds commas to a large number:

salary = 1250000
print(f"Salary: {salary:,}")

Output

Salary: 1,250,000

You can combine the two. :,.2f gives you commas and two decimals together.

Alignment and width

You can also reserve space for a value and line things up. You give a width number. Then one of these signs decides which side it hugs:

Symbol Meaning
< Left align (text starts at the left)
> Right align (text ends at the right)
^ Center align

This pads each name to a width of 10 so the prices below line up neatly:

print(f"{'Apple':<10}{'$2.00':>8}")
print(f"{'Banana':<10}{'$1.50':>8}")

Output

Apple $2.00
Banana $1.50

The <10 keeps each name on the left and gives it 10 characters of room. The >8 pushes each price to the right edge of an 8-character space. That is how you get clean columns without counting spaces by hand.

🧾 A Real Example: A Formatted Bill

Let us put it together. Say Riya buys a few items. We want a tidy receipt with prices lined up and a total at the bottom.

This builds a small receipt using width and decimal specs together:

items = [
("Coffee", 4.5),
("Sandwich", 7.25),
("Cookie", 2.0),
]
total = 0
print(f"{'Item':<12}{'Price':>8}")
print("-" * 20)
for name, price in items:
total += price
print(f"{name:<12}{price:>8.2f}")
print("-" * 20)
print(f"{'Total':<12}{total:>8.2f}")

Output

Item Price
--------------------
Coffee 4.50
Sandwich 7.25
Cookie 2.00
--------------------
Total 13.75

Look at what each spec is doing:

  • {'Item':<12} and {name:<12} keep the labels on the left, each 12 wide.
  • {price:>8.2f} does two jobs at once. The >8 lines prices up on the right. The .2f shows two decimals.
  • "-" * 20 is a quick trick to draw a divider line 20 characters long.

That is real formatting doing real work. Neat columns. Money shown correctly. No manual spacing.

📜 The Older Ways: str.format() and %

F-strings are new. Plenty of older code still uses two earlier styles. So you should recognize them when you see them.

The str.format() method uses empty braces and fills them from the arguments you pass:

name = "Alex"
score = 92.5
print("Name: {}, Score: {}".format(name, score))

Output

Name: Alex, Score: 92.5

The format specs work the same here. You write them inside the braces just like in f-strings. For example {:.2f}.

The oldest style is % formatting. It uses %s for strings, %d for whole numbers, and %f for floats:

name = "Alex"
score = 92.5
print("Name: %s, Score: %.2f" % (name, score))

Output

Name: Alex, Score: 92.50

Both of these still run fine. But for new code, reach for f-strings. They put the value right next to where it appears in the text. So the line is much easier to read.

Note

You do not need to memorize the % style. Just know that %s, %d, and %.2f mean “a string here”, “a whole number here”, and “a float with two decimals here”. That is enough to read old code.

⚠️ Common Mistakes

A few small things trip people up. Watch out for these.

Forgetting the f. Without it, the braces stay as plain text.

name = "Alex"
# ❌ Avoid: no f, so the braces are not replaced
print("Hello {name}") # prints: Hello {name}
# ✅ Good: the f makes it an f-string
print(f"Hello {name}") # prints: Hello Alex

Putting the spec on the wrong side. The format spec always comes after a colon, inside the braces.

price = 9.5
# ❌ Avoid: spec outside the braces does nothing useful
print(f"{price}.2f")
# ✅ Good: colon and spec live inside the braces
print(f"{price:.2f}")

Mixing up quotes. If your f-string uses double quotes on the outside, use single quotes inside the braces, like {'Apple':<10}. Otherwise Python gets confused about where the string ends.

✅ Best Practices

  • Use f-strings for any new code you write. They are the clearest option.
  • Always show money with :.2f so prices never come out as 4.5 when you mean 4.50.
  • Keep the logic inside braces small. If a calculation gets long, do it on its own line first. Then drop the result into the f-string.
  • Use width specs to build columns instead of typing spaces by hand. It stays lined up even when values change.

🧩 What You’ve Learned

✅ String formatting lets you drop values into text without messy + signs or str() calls.

✅ F-strings are the modern way. Put an f before the quote and your value inside { }.

✅ Format specs after a colon control how values look. :.2f for two decimals, :, for commas, <, >, ^ for alignment and width.

✅ You can run small expressions and math right inside the braces.

str.format() and % are older styles you will see in old code. But f-strings are the recommended choice.

Check Your Knowledge

Test what you learned. Pick an answer for each question, then click Check.

  1. 1

    What does the f before the opening quote in f"Hello {name}" do?

    Why: The f marks the string as an f-string, so anything inside the braces gets evaluated and inserted.

  2. 2

    How do you display the number 9.5 as 9.50 inside an f-string?

    Why: The spec :.2f shows the value as a float with exactly two digits after the decimal point.

  3. 3

    What does the spec :>8 do to a value inside an f-string?

    Why: The > means right-align and the 8 is the width, so the value hugs the right edge of an 8-character space.

  4. 4

    Which formatting style is recommended for new Python code?

    Why: F-strings are short and put the value right next to where it appears, making them the clearest choice for new code.

🚀 What’s Next?

You can build neat strings now. Next you will learn how to look inside a string to find words and check what it contains.

String Searching

Share & Connect