Python
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Data Types
-
Section 3: Collections
-
39: Set Operations: Union, Intersection, Difference
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Turtle Graphics and Early Practice Projects
-
Section 7: Working with Files and I/O
-
Section 8: Regular Expressions
-
Section 9: Object-Oriented Python
-
Section 10: Error Handling
-
Section 11: Modules and Packages
-
Section 12: Iterators, Generators, and Functional Tools
-
Section 13: Decorators and Metaprogramming
-
Section 14: Concurrency and Parallelism
-
Section 15: Working with Dates, Times, and Numbers
-
Section 16: Standard Library Deep Dive I: Data Structures
-
Section 17: Standard Library Deep Dive II: System and Introspection
-
Section 18: Standard Library Deep Dive III: Security and Encoding
-
Section 19: Standard Library Deep Dive IV: Text and Data Utilities
-
Section 20: Networking and Web Basics
-
Section 21: Working with Databases
-
Section 22: Testing and Quality
-
Section 23: Advanced Typing
-
Section 24: Context Managers and Resource Handling
-
Section 25: Text, Unicode, and Binary Data
-
Section 26: More Functional and Iteration Tools
-
Section 27: Data Validation and Configuration
-
Section 28: Working with Images and Media
-
Section 29: Property-Based and Documentation Testing
-
Section 30: Packaging and Deployment
-
Section 31: Performance and Internals
-
Section 32: Design Patterns in Python
-
Section 33: GUI Programming
-
Section 34: Security Basics
-
Section 35: Data Structures and Algorithms
-
Section 36: Practical Projects
-
Section 37: Capstone Projects
-
Section 38: Interview and Algorithm Practice
-
Section 39: Writing Idiomatic Python
22: String Formatting with f-Strings
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.50hours_worked = 12.75discount_percent = 0.10(10% discount)
Write a script using f-strings to produce a summary that meets these exact requirements:
- The client name must be centered in a 20-character wide field.
- The subtotal (
hourly_rate * hours_worked) must be displayed with exactly 2 decimal places. - The discount amount must be displayed as a percentage (e.g.,
10.0%) using the:.1%format specifier. - 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
There are no comments for now.