Skip to Content
Course content

22: String Formatting with f-Strings

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

A few years ago, I was reviewing a pull request for a junior developer who was building a system monitoring tool. He had written a block of code to log server alerts that looked like a nightmare of plus signs and str() conversions. It looked something like "Alert: Server " + server_name + " is at " + str(cpu_load) + "% capacity." It wasn't just hard to read; he'd actually missed a space between the server name and the word "is," making the logs look like ServerProduction-01is at 98%. It's a classic mistake, and it's exactly why we have f-strings.

Introduced in Python 3.6, f-strings (formatted string literals) are the gold standard for putting data into strings. They aren't just "syntactic sugar"—they are faster than the old % operator and the .format() method because they are evaluated at runtime rather than being parsed as a constant template. You just prefix the string with an f or F, and suddenly, anything inside curly braces {} is treated as live Python code.

Injecting Variables and Expressions

The most basic use case is dropping a variable directly into a string. But you aren't limited to just variables; you can run almost any valid Python expression inside those braces. I often use this to handle quick transformations without needing to create a temporary variable on the line above.

user_name = "jake_the_snake"
login_attempts = 3

# Instead of multiple lines, do it all in the string
message = f"User {user_name.upper()} has failed {login_attempts * 2} security checks."
print(message) 
# Output: User JAKE_THE_SNAKE has failed 6 security checks.

It's much more intuitive to read from left to right, exactly how the final sentence will appear. Just be careful not to put too much logic in there—if you find yourself writing a complex if-else statement inside an f-string, your teammates will probably give you a funny look during code review. Keep it simple.

Taming Decimals and Alignment

If you've ever tried to print a list of prices, you know that Python loves to give you 19.990000000000002 instead of 19.99. This is where the "format specifier" comes in. By adding a colon : inside the braces, you can tell Python exactly how to render the value.

price = 49.9582
tax_rate = 0.0725

# .2f means "fixed-point float with 2 decimal places"
print(f"The total price is ${price + (price * tax_rate):.2f}")
# Output: The total price is $53.56

I also frequently use f-strings to create clean, tabular output in the console without needing a heavy library like Pandas. You can specify a width and an alignment: < for left, > for right, and ^ for center.

servers = [("Web-01", "Online"), ("DB-01", "Offline"), ("Cache-01", "Online")]

for name, status in servers:
    # Name is left-aligned (10 chars), status is right-aligned (10 chars)
    print(f"{name:<10} | {status:>10}")

The Debugging Shortcut

This is my favorite "hidden" feature, added in Python 3.8. When you're debugging, you usually write something like print(f"user_id: {user_id}"). It's tedious. Instead, you can just add an equals sign = after the variable name inside the brace.

api_key = "sk_test_4eC39HqLyjWDarjtT1zdp7dc"
timeout = 30

print(f"{api_key=}, {timeout=}")
# Output: api_key='sk_test_4eC39HqLyjWDarjtT1zdp7dc', timeout=30

It automatically prints the variable name and its value. It’s a massive time-saver when you're hunting down a bug in a complex loop and don't want to manually type out every label.




📋 Practical Task

Exercise: Professional Invoice Generator

You are tasked with creating a clean, formatted invoice summary for a freelance client. You have the following raw data:

  • client_name = "Acme Corp"
  • hourly_rate = 125.50
  • hours_worked = 12.75
  • discount_percent = 0.10 (10% discount)

Write a script using f-strings to produce a summary that meets these exact requirements:

  1. The client name must be centered in a 20-character wide field.
  2. The subtotal (hourly_rate * hours_worked) must be displayed with exactly 2 decimal places.
  3. The discount amount must be displayed as a percentage (e.g., 10.0%) using the :.1% format specifier.
  4. The final total (subtotal minus discount) must be formatted as currency with a dollar sign and 2 decimal places.

Example Expected Output:
Acme Corp
Subtotal: $1600.13
Discount: 10.0%
Total: $1440.11

Rating
0 0

There are no comments for now.

to be the first to leave a comment.