Python

Python Fundamentals

String Formatting

Concatenating strings with + gets messy fast, especially mixing types:

JrCodex·4 min read

Jr Codex Python Notes

Level: Beginner Prerequisites: Chapter 4 Time to complete: ~20 minutes


Table of Contents

  1. Why Formatting Matters
  2. f-strings (the Modern Standard)
  3. Formatting Numbers
  4. The .format() Method
  5. Old-Style % Formatting
  6. Which Style Should You Use?
  7. Summary & Next Steps

1. Why Formatting Matters

Concatenating strings with + gets messy fast, especially mixing types:

name = "Alice"
age = 25
 
# Clunky and error-prone
message = "Name: " + name + ", Age: " + str(age)

Python gives you three ways to embed values into strings. This chapter covers all three, but you'll mostly use the first one.


2. f-strings (the Modern Standard)

Introduced in Python 3.6, f-strings are the preferred way to format strings today. Prefix the string with f and embed expressions in {}.

name = "Alice"
age = 25
 
message = f"Name: {name}, Age: {age}"
print(message)     # Name: Alice, Age: 25

You can put any valid expression inside {}, not just variable names:

a, b = 5, 3
print(f"{a} + {b} = {a + b}")          # 5 + 3 = 8
 
user = {"name": "Bob"}
print(f"Hello, {user['name']}!")       # Hello, Bob!
 
def shout(text):
    return text.upper()
print(f"{shout('hi')}")                 # HI

Debugging with = (Python 3.8+)

x = 42
print(f"{x=}")     # x=42 — prints both the expression and its value, great for quick debugging

3. Formatting Numbers

f-strings support a format spec after a colon — this is where most of the day-to-day power lives:

price = 1234.5678
pi = 3.14159265
 
print(f"{price:.2f}")        # 1234.57   — 2 decimal places
print(f"{price:,.2f}")       # 1,234.57  — thousands separator + 2 decimals
print(f"{pi:.3f}")           # 3.142     — 3 decimal places
 
count = 7
print(f"{count:03d}")        # 007       — zero-padded to 3 digits
 
ratio = 0.4567
print(f"{ratio:.1%}")        # 45.7%     — percentage formatting
 
print(f"{42:>8}")             # "      42" — right-align in 8-char width
print(f"{42:<8}|")            # "42      |" — left-align
print(f"{42:^8}|")            # "   42   |" — center-align
SpecMeaningExample
.2fFixed-point, 2 decimals3.141593.14
,Thousands separator12345671,234,567
03dZero-pad integer to width 37007
.1%Percentage, 1 decimal0.45745.7%
>, <, ^Align right/left/centersee above

4. The .format() Method

Predates f-strings (Python 2.7+) and is still common in older codebases:

name = "Alice"
age = 25
 
print("Name: {}, Age: {}".format(name, age))         # positional
print("Name: {n}, Age: {a}".format(n=name, a=age))   # named
print("{0} is {1}. {0} lives here.".format(name, age)) # indexed, reusable
 
print("{:.2f}".format(3.14159))    # 3.14 — same format specs as f-strings

5. Old-Style % Formatting

The oldest style, inherited from C's printf. You'll mainly recognize it when reading legacy code:

name = "Alice"
age = 25
 
print("Name: %s, Age: %d" % (name, age))    # Name: Alice, Age: 25
print("Pi is %.2f" % 3.14159)                # Pi is 3.14
SpecifierType
%sString
%dInteger
%fFloat

6. Which Style Should You Use?

Recommendation:
──────────────────────────────────────────────
  New code            →  f-strings   (fastest, most readable)
  Reading legacy code  →  recognize .format() and %-formatting
  Logging templates     →  sometimes %-style (deferred evaluation,
                            e.g. logging.info("%s", value))
──────────────────────────────────────────────

All three examples below produce the identical output — but only the first is recommended for new code:

name, age = "Alice", 25
 
print(f"{name} is {age}")              # ✓ preferred
print("{} is {}".format(name, age))    # acceptable, older codebases
print("%s is %d" % (name, age))        # legacy, avoid in new code

7. Summary & Next Steps

Key Takeaways

  • f-strings (f"{expr}") are the modern standard — readable, fast, support inline expressions and format specs.
  • Format specs (:.2f, :,, :03d, :.1%) control decimals, separators, padding, and percentages.
  • .format() and %-formatting still appear in real (often older) codebases — recognize them even if you don't write new code with them.

Concept Check

  1. Rewrite "Total: " + str(total) as an f-string.
  2. What does f"{value:.2f}" do to value = 3.14159?
  3. What's the output of f"{7:03d}"?

Next Chapter

Chapter 6: Lists


Jr Codex — 1-on-1 Personalized Coaching | Back to Module Index