Skip to Content
Course content

23: String Formatting with .format() and %

Click on the "Edit" button in the top corner of the screen to edit your slide content.

When you first start building scripts, your instinct is usually to glue strings together using the + operator. It seems intuitive—you have a piece of text, you have a variable, and you just want them to sit next to each other. But once you're dealing with more than two variables or mixing in numbers, that approach becomes a nightmare to maintain.

The Mess of Plus Signs

Imagine you're writing a monitoring script that alerts you when a server is overheating. You have a server name, a current temperature, and a threshold. If you do this the naive way, it looks something like this:

server_name = "prod-db-01"
temp = 82.456
threshold = 80

print("ALERT: Server " + server_name + " has exceeded the threshold of " + str(threshold) + "°C. Current temp: " + str(temp) + "°C.")

Do you see how exhausting that is to write? You're constantly opening and closing quotes, manually adding spaces, and—the biggest pain—wrapping every single number in a str() call because Python won't let you add a float to a string. It's visually noisy, and if you need to change the phrasing of the sentence, you have to carefully dismantle a chain of plus signs. It's a recipe for a TypeError.

The Legacy of the Percent Sign

Before the more modern methods arrived, we used the % operator, often called "printf-style formatting." It allows you to define a template with placeholders and then fill them in at the end. It’s a massive upgrade over concatenation because it handles the type conversion for you.

# Much cleaner, no str() calls needed
print("ALERT: Server %s has exceeded the threshold of %d°C. Current temp: %.2f°C." % (server_name, threshold, temp))

I still see this everywhere in older codebases. The %s tells Python to treat the value as a string, %d as an integer, and %.2f tells it to format a float to exactly two decimal places. It's concise, but it has a rigid weakness: it's strictly positional. If you have ten variables and want to swap the second and the fifth, you have to carefully reorder the tuple at the end of the line, which is where a lot of bugs sneak in.

The Flexibility of .format()

To solve that rigidity, Python introduced the .format() method. Instead of specific type codes like %d, it uses curly braces {} as general placeholders. This is the "sweet spot" for many developers because it separates the template from the data more cleanly.

print("ALERT: Server {0} has exceeded the threshold of {1}°C. Current temp: {2:.2f}°C.".format(server_name, threshold, temp))

The real power here is that you can use indices or even keyword arguments. If I want to reuse the server name twice in one long message, I don't have to pass the variable into the function twice; I just reference {0} again. Or, for maximum clarity, I can name my placeholders:

print("Server {name} is hot! {temp:.1f}C is over the {limit}C limit.".format(name=server_name, temp=temp, limit=threshold))

When you use keywords, the order no longer matters. You're explicitly stating which piece of data goes where. It makes the code self-documenting. While you'll likely use f-strings for most of your new work, you absolutely need to be comfortable with .format() and % because they are the backbone of thousands of existing libraries and legacy systems you'll encounter in the wild.




📋 Practical Task

Build a Formatted E-commerce Order Summary

You are tasked with creating a printable order summary for a customer. Instead of using string concatenation, use the .format() method with keyword arguments to build the summary. This ensures that if the order of the variables changes in the future, the message remains correct.

Create a script with the following variables:

  • customer_name (e.g., "Alice Smith")
  • order_id (e.g., 55021)
  • total_price (e.g., 124.99)
  • item_count (e.g., 3)

Your output should be a single string formatted exactly like this (with the variables filled in):
Order #55021 for Alice Smith: 3 items total. Amount due: $124.99

Requirement: Use .format(name=value, ...) to map your variables to the placeholders in the string.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.