String Formatting
String Formatting
Section titled “String Formatting”Introduction
Section titled “Introduction”Python offers three ways to format strings. f-strings (Python 3.6+) are the preferred approach.
f-strings (Preferred ✅)
Section titled “f-strings (Preferred ✅)”name = "Alice"age = 30score = 98.765
# Basicprint(f"Name: {name}, Age: {age}")
# Expressionsprint(f"In 10 years: {age + 10}")print(f"Upper: {name.upper()}")
# Format specsprint(f"Score: {score:.2f}") # 98.77print(f"Score: {score:10.2f}") # Right-alignedprint(f"Millions: {1_000_000:,}") # 1,000,000
# Debugging (Python 3.8+)x = 42print(f"{x=}") # x=42.format() Method (Python 3.0+)
Section titled “.format() Method (Python 3.0+)”name = "Alice"age = 30
print("Name: {}, Age: {}".format(name, age))print("{0} is {1} years old".format(name, age))print("{name} is {age} years old".format(name="Bob", age=25))
print("{:b}".format(255)) # 11111111 (binary)print("{:x}".format(255)) # ff (hex)print("{:e}".format(0.001234)) # 1.234000e-03% Formatting (Old Style)
Section titled “% Formatting (Old Style)”name = "Alice"age = 30score = 98.765
print("Name: %s, Age: %d, Score: %.2f" % (name, age, score))Format Specification Mini-Language
Section titled “Format Specification Mini-Language”print(f"{'hi':*^10}") # '****hi****'print(f"{42:+}") # '+42'print(f"{3.14159:.3f}") # '3.142'print(f"{255:b}") # '11111111'print(f"{1000000:,}") # '1,000,000'Why It Matters
Section titled “Why It Matters”Proper string formatting is essential for creating readable logs, user-facing messages, and data reports.
Interview Questions
Section titled “Interview Questions”Q1: Why are f-strings preferred over .format() and % formatting?
A: f-strings are more readable (inline expressions), faster (compile-time evaluation), and support any Python expression inside {}.
Q2: How do you round a float to 2 decimal places in an f-string?
A: f"{value:.2f}" — the .2f format specifier rounds to 2 decimal places.
Practice Exercises
Section titled “Practice Exercises”- Format a number as currency with commas and 2 decimal places.
- Create a formatted table of student names and scores.
- Use f-string debugging to print variable names and values.