Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Creating dynamic text—such as automated invoices, personalized email alerts, or server status logs—requires combining static sentences with dynamic variables. Over its multi-decade evolution, Python has developed three distinct generations of string formatting:
% Formatting (Legacy Python 2): C-style printf interpolation.str.format() (Python 2.6 / 3.0): Placeholder-based template engine.f-strings (Formatted String Literals, Python 3.6+): The modern, blazingly fast, and readable industry standard.Today, f-strings are the universal gold standard across all production Python codebases.
+-------------------------------------------------------------------------+
| STRING FORMATTING REAL-WORLD ANALOGY |
+-------------------------------------------------------------------------+
1. % FORMATTING (Old Lead Block Printing Press):
- A 19th-century mechanical press with metal lead blocks (%s, %d).
- If you accidentally swap the order of the groom's name and wedding date,
the press stamps: "25th December weds Rahul on Sharma"!
- Fragile, difficult to maintain, and strictly positional.
2. str.format() (Mail Merge Templates):
- A Word template: "{0} invites you to the wedding of {1} on {2}."
- Better because placeholders can be numbered, but still verbose
because variable names are separated at the far end of the sentence.
3. MODERN f-strings (Airport Smart Display Board):
- The variable is embedded directly into the exact slot:
f"Welcome {passenger}, Flight {flight_no} boards at Gate {gate}."
- Instant clarity, no mental counting of placeholders, and allows
on-the-fly math and currency formatting!
+-------------------------------------------------------------------------+Inside an f-string, anything enclosed in curly braces {} is treated as active Python code. You can attach a format specifier following a colon ::
+ vs str.join()You can concatenate strings using the + operator. However, using + inside a loop to assemble large text is an $O(N^2)$ memory anti-pattern because every + creates an entirely new string in memory.
Compare the exact same formatting task across all three paradigms:
Inside {} in an f-string, you are not limited to variable names; you can execute any valid Python expression:
f"{var=}")Introduced in Python 3.8, appending an equals sign = inside an f-string prints both the expression itself and its evaluated result. This is a game-changer for quick terminal debugging:
| Scenario | Anti-Pattern (Don't) | Best Practice (Do) | Why |
|---|---|---|---|
| Dynamic Strings | "Total: " + str(total) | f"Total: {total}" | f-strings automatically cast any object and run 2x-3x faster. |
| Large Assembly | s = ""; for w in words: s += w | "".join(words) | += in loops creates $O(N^2)$ memory churn; .join() is $O(N)$. |
| Float Precision | round(amt, 2) inside text | f"{amt:.2f}" | round(10.0, 2) prints 10.0; {amt:.2f} enforces 10.00. |
| Console Debugging | print("x:", x, "y:", y) | print(f"{x=}, {y=}") | Self-documenting = syntax saves keystrokes and clarifies logs. |
+-------------------------------------------------------------------------+
| STRING FORMATTING CHEAT SHEET |
+-------------------------------------------------------------------------+
- Modern Standard: f"Hello {name}, you scored {score:.2f}%"
- Decimal Rounding: {val:.2f} (2 decimal places)
- Thousand Commas: {val:,.2f} (e.g. 1,250,000.50)
- Alignment: {val:<10} Left, {val:>10} Right, {val:^10} Center
- Percentages: {0.18:.1%} -> 18.0%
- Fast Debugging: f"{x=}" -> x=42
- Joining Lists: ", ".join(my_list)
+-------------------------------------------------------------------------+Python strings are immutable. You cannot assign directly to a character index:
In Python slicing text[start:stop], the stop index is exclusive (not included in the slice):
A. Python 2.7 B. Python 3.0 C. Python 3.6 D. Python 3.12
A. {price:%2c} B. {price:,.2f} C. {price:2.comma} D. {price:.2d}
x = 25; print(f"{x=}") in Python 3.8+?A. "25" B. "x=25" C. "x" D. SyntaxError
f"{0.085:.1%}"?A. "0.085%" B. "8.5%" C. "85%" D. "0.1%"
+= inside a loop considered an anti-pattern compared to str.join()?A. Python does not permit += on strings B. Strings are immutable, so each += creates and destroys an entirely new string object in memory, causing $O(N^2)$ performance degradation C. str.join() is only compatible with numbers D. += deletes the first character of the string
Write a complete, runnable Python script that generates an official, beautifully aligned monthly employee salary slip. The program must format basic pay, HRA, Provident Fund (PF), and Professional Tax using f-strings with table alignment (<, >, ^), comma thousand separators, and debug telemetry.
In the next lesson, we will continue your Python learning journey with Escape Characters (5: Strings).
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Modifying Strings | Escape Characters |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.