String Processing
F-Strings
Creating readable, formatted output is a common programming task. F-strings (formatted string literals) provide the most concise and readable way to embed Python expressions directly in strings. They are faster than older methods and support full Python expressions inside curly braces.
F-strings (formatted string literals) provide a concise way to embed expressions inside string literals using the f prefix and curly braces {}.
Basic Syntax
basics.py
Replay: real traced execution (multi-file project)
# Basic f-strings
# Simple variable embedding
name = "Alice"
age = 25
# Basic f-string
greeting = f"Hello, {name}!"
print(greeting)
# Multiple variables
message = f"{name} is {age} years old"
print(message)
# Without f-string (for comparison)
old_way = "Hello, " + name + "!"
print("Old way:", old_way)
# Expressions in f-strings
x = 10
y = 20
# Arithmetic
print(f"{x} + {y} = {x + y}")
print(f"{x} * {y} = {x * y}")
# Comparison
print(f"{x} < {y} is {x < y}")
# Function calls
text = "hello"
print(f"Uppercase: {text.upper()}")
print(f"Length: {len(text)}")
# Different data types
name = "Bob"
age = 30
height = 1.75
is_active = True
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Height: {height}m")
print(f"Active: {is_active}")
# Multi-line f-strings
item = "Widget"
price = 19.99
quantity = 5
description = f"""
Product: {item}
Price: ${price}
Quantity: {quantity}
Total: ${price * quantity}
"""
print(description)
# Basic f-strings
# Simple variable embedding
name = "Maya"
age = 25
# Basic f-string
greeting = f"Hello, {name}!"
print(greeting)
# Multiple variables
message = f"{name} is {age} years old"
print(message)
# Without f-string (for comparison)
old_way = "Hello, " + name + "!"
print("Old way:", old_way)
# Expressions in f-strings
x = 10
y = 20
# Arithmetic
print(f"{x} + {y} = {x + y}")
print(f"{x} * {y} = {x * y}")
# Comparison
print(f"{x} < {y} is {x < y}")
# Function calls
text = "hello"
print(f"Uppercase: {text.upper()}")
print(f"Length: {len(text)}")
# Different data types
name = "Bob"
age = 30
height = 1.75
is_active = True
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Height: {height}m")
print(f"Active: {is_active}")
# Multi-line f-strings
item = "Widget"
price = 19.99
quantity = 5
description = f"""
Product: {item}
Price: ${price}
Quantity: {quantity}
Total: ${price * quantity}
"""
print(description)
# Basic f-strings
# Simple variable embedding
name = "Jordan"
age = 25
# Basic f-string
greeting = f"Hello, {name}!"
print(greeting)
# Multiple variables
message = f"{name} is {age} years old"
print(message)
# Without f-string (for comparison)
old_way = "Hello, " + name + "!"
print("Old way:", old_way)
# Expressions in f-strings
x = 10
y = 20
# Arithmetic
print(f"{x} + {y} = {x + y}")
print(f"{x} * {y} = {x * y}")
# Comparison
print(f"{x} < {y} is {x < y}")
# Function calls
text = "hello"
print(f"Uppercase: {text.upper()}")
print(f"Length: {len(text)}")
# Different data types
name = "Bob"
age = 30
height = 1.75
is_active = True
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Height: {height}m")
print(f"Active: {is_active}")
# Multi-line f-strings
item = "Widget"
price = 19.99
quantity = 5
description = f"""
Product: {item}
Price: ${price}
Quantity: {quantity}
Total: ${price * quantity}
"""
print(description)
# Basic f-strings
# Simple variable embedding
name = "Alice"
age = 17
# Basic f-string
greeting = f"Hello, {name}!"
print(greeting)
# Multiple variables
message = f"{name} is {age} years old"
print(message)
# Without f-string (for comparison)
old_way = "Hello, " + name + "!"
print("Old way:", old_way)
# Expressions in f-strings
x = 10
y = 20
# Arithmetic
print(f"{x} + {y} = {x + y}")
print(f"{x} * {y} = {x * y}")
# Comparison
print(f"{x} < {y} is {x < y}")
# Function calls
text = "hello"
print(f"Uppercase: {text.upper()}")
print(f"Length: {len(text)}")
# Different data types
name = "Bob"
age = 30
height = 1.75
is_active = True
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Height: {height}m")
print(f"Active: {is_active}")
# Multi-line f-strings
item = "Widget"
price = 19.99
quantity = 5
description = f"""
Product: {item}
Price: ${price}
Quantity: {quantity}
Total: ${price * quantity}
"""
print(description)
# Basic f-strings
# Simple variable embedding
name = "Alice"
age = 42
# Basic f-string
greeting = f"Hello, {name}!"
print(greeting)
# Multiple variables
message = f"{name} is {age} years old"
print(message)
# Without f-string (for comparison)
old_way = "Hello, " + name + "!"
print("Old way:", old_way)
# Expressions in f-strings
x = 10
y = 20
# Arithmetic
print(f"{x} + {y} = {x + y}")
print(f"{x} * {y} = {x * y}")
# Comparison
print(f"{x} < {y} is {x < y}")
# Function calls
text = "hello"
print(f"Uppercase: {text.upper()}")
print(f"Length: {len(text)}")
# Different data types
name = "Bob"
age = 30
height = 1.75
is_active = True
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Height: {height}m")
print(f"Active: {is_active}")
# Multi-line f-strings
item = "Widget"
price = 19.99
quantity = 5
description = f"""
Product: {item}
Price: ${price}
Quantity: {quantity}
Total: ${price * quantity}
"""
print(description)
name ← Alice, age ← 25, greeting ← Hello, Alice!, message ← Alice is 25 years old
4# Simple variable embedding5name→ Alice = "Alice"6#@name="Maya", "Jordan"7age→ 25 = 258#@age=17, 42910# Basic f-string11greeting→ Hello, Alice! = f"Hello, {nameAlice}!"12print(greetingHello, Alice!)1314# Multiple variables15message→ Alice is 25 years old = f"{nameAlice} is {age25} years old"16print(messageAlice is 25 years old)1718# Without f-string (for comparison)19old_way→ Hello, Alice! = "Hello, " + nameAlice + "!"20print("Old way:", old_wayHello, Alice!)2122# Expressions in f-strings23x→ 10 = 1024y→ 20 = 202526# Arithmetic27print(f"{x10} + {y20} = {x + y}")28print(f"{x10} * {y20} = {x * y}")2930# Comparison31print(f"{x10} < {y20} is {x < y}")3233# Function calls34text→ hello = "hello"35print(f"Uppercase: {texthello.upper()}")36print(f"Length: {len(texthello)}")3738# Different data types39name→ Bob = "Bob"40age→ 30 = 3041height→ 1.75 = 1.7542is_active→ True = True4344print(f"Name: {nameBob}")45print(f"Age: {age30}")46print(f"Height: {height1.75}m")47print(f"Active: {is_activeTrue}")4849# Multi-line f-strings50item→ Widget = "Widget"51price→ 19.99 = 19.9952quantity→ 5 = 55354description→ Product: Widget Price: $19.99 Quantity: 5 Total: $99.94999999999999 = f"""55Product: {itemWidget}56Price: ${price19.99}57Quantity: {quantity5}58Total: ${price19.99 * quantity5}59"""60print(description Product: Widget Price: $19.99 Quantity: 5 Total: $99.94999999999999 )outputHello, Alice! Alice is 25 years old Old way: Hello, Alice! 10 + 20 = 30 10 * 20 = 200 10 < 20 is True Uppercase: HELLO Length: 5 Name: Bob Age: 30 Height: 1.75m Active: True Product: Widget Price: $19.99 Quantity: 5 Total: $99.94999999999999
name ← Maya, age ← 25, greeting ← Hello, Maya!, message ← Maya is 25 years old
4# Simple variable embedding5name→ Maya = "Maya"6age→ 25 = 2578# Basic f-string9greeting→ Hello, Maya! = f"Hello, {nameMaya}!"10print(greetingHello, Maya!)1112# Multiple variables13message→ Maya is 25 years old = f"{nameMaya} is {age25} years old"14print(messageMaya is 25 years old)1516# Without f-string (for comparison)17old_way→ Hello, Maya! = "Hello, " + nameMaya + "!"18print("Old way:", old_wayHello, Maya!)1920# Expressions in f-strings21x→ 10 = 1022y→ 20 = 202324# Arithmetic25print(f"{x10} + {y20} = {x + y}")26print(f"{x10} * {y20} = {x * y}")2728# Comparison29print(f"{x10} < {y20} is {x < y}")3031# Function calls32text→ hello = "hello"33print(f"Uppercase: {texthello.upper()}")34print(f"Length: {len(texthello)}")3536# Different data types37name→ Bob = "Bob"38age→ 30 = 3039height→ 1.75 = 1.7540is_active→ True = True4142print(f"Name: {nameBob}")43print(f"Age: {age30}")44print(f"Height: {height1.75}m")45print(f"Active: {is_activeTrue}")4647# Multi-line f-strings48item→ Widget = "Widget"49price→ 19.99 = 19.9950quantity→ 5 = 55152description→ Product: Widget Price: $19.99 Quantity: 5 Total: $99.94999999999999 = f"""53Product: {itemWidget}54Price: ${price19.99}55Quantity: {quantity5}56Total: ${price19.99 * quantity5}57"""58print(description Product: Widget Price: $19.99 Quantity: 5 Total: $99.94999999999999 )outputHello, Maya! Maya is 25 years old Old way: Hello, Maya! 10 + 20 = 30 10 * 20 = 200 10 < 20 is True Uppercase: HELLO Length: 5 Name: Bob Age: 30 Height: 1.75m Active: True Product: Widget Price: $19.99 Quantity: 5 Total: $99.94999999999999
name ← Jordan, age ← 25, greeting ← Hello, Jordan!, message ← Jordan is 25 years old
4# Simple variable embedding5name→ Jordan = "Jordan"6age→ 25 = 2578# Basic f-string9greeting→ Hello, Jordan! = f"Hello, {nameJordan}!"10print(greetingHello, Jordan!)1112# Multiple variables13message→ Jordan is 25 years old = f"{nameJordan} is {age25} years old"14print(messageJordan is 25 years old)1516# Without f-string (for comparison)17old_way→ Hello, Jordan! = "Hello, " + nameJordan + "!"18print("Old way:", old_wayHello, Jordan!)1920# Expressions in f-strings21x→ 10 = 1022y→ 20 = 202324# Arithmetic25print(f"{x10} + {y20} = {x + y}")26print(f"{x10} * {y20} = {x * y}")2728# Comparison29print(f"{x10} < {y20} is {x < y}")3031# Function calls32text→ hello = "hello"33print(f"Uppercase: {texthello.upper()}")34print(f"Length: {len(texthello)}")3536# Different data types37name→ Bob = "Bob"38age→ 30 = 3039height→ 1.75 = 1.7540is_active→ True = True4142print(f"Name: {nameBob}")43print(f"Age: {age30}")44print(f"Height: {height1.75}m")45print(f"Active: {is_activeTrue}")4647# Multi-line f-strings48item→ Widget = "Widget"49price→ 19.99 = 19.9950quantity→ 5 = 55152description→ Product: Widget Price: $19.99 Quantity: 5 Total: $99.94999999999999 = f"""53Product: {itemWidget}54Price: ${price19.99}55Quantity: {quantity5}56Total: ${price19.99 * quantity5}57"""58print(description Product: Widget Price: $19.99 Quantity: 5 Total: $99.94999999999999 )outputHello, Jordan! Jordan is 25 years old Old way: Hello, Jordan! 10 + 20 = 30 10 * 20 = 200 10 < 20 is True Uppercase: HELLO Length: 5 Name: Bob Age: 30 Height: 1.75m Active: True Product: Widget Price: $19.99 Quantity: 5 Total: $99.94999999999999
name ← Alice, age ← 17, greeting ← Hello, Alice!, message ← Alice is 17 years old
4# Simple variable embedding5name→ Alice = "Alice"6age→ 17 = 1778# Basic f-string9greeting→ Hello, Alice! = f"Hello, {nameAlice}!"10print(greetingHello, Alice!)1112# Multiple variables13message→ Alice is 17 years old = f"{nameAlice} is {age17} years old"14print(messageAlice is 17 years old)1516# Without f-string (for comparison)17old_way→ Hello, Alice! = "Hello, " + nameAlice + "!"18print("Old way:", old_wayHello, Alice!)1920# Expressions in f-strings21x→ 10 = 1022y→ 20 = 202324# Arithmetic25print(f"{x10} + {y20} = {x + y}")26print(f"{x10} * {y20} = {x * y}")2728# Comparison29print(f"{x10} < {y20} is {x < y}")3031# Function calls32text→ hello = "hello"33print(f"Uppercase: {texthello.upper()}")34print(f"Length: {len(texthello)}")3536# Different data types37name→ Bob = "Bob"38age→ 30 = 3039height→ 1.75 = 1.7540is_active→ True = True4142print(f"Name: {nameBob}")43print(f"Age: {age30}")44print(f"Height: {height1.75}m")45print(f"Active: {is_activeTrue}")4647# Multi-line f-strings48item→ Widget = "Widget"49price→ 19.99 = 19.9950quantity→ 5 = 55152description→ Product: Widget Price: $19.99 Quantity: 5 Total: $99.94999999999999 = f"""53Product: {itemWidget}54Price: ${price19.99}55Quantity: {quantity5}56Total: ${price19.99 * quantity5}57"""58print(description Product: Widget Price: $19.99 Quantity: 5 Total: $99.94999999999999 )outputHello, Alice! Alice is 17 years old Old way: Hello, Alice! 10 + 20 = 30 10 * 20 = 200 10 < 20 is True Uppercase: HELLO Length: 5 Name: Bob Age: 30 Height: 1.75m Active: True Product: Widget Price: $19.99 Quantity: 5 Total: $99.94999999999999
name ← Alice, age ← 42, greeting ← Hello, Alice!, message ← Alice is 42 years old
4# Simple variable embedding5name→ Alice = "Alice"6age→ 42 = 4278# Basic f-string9greeting→ Hello, Alice! = f"Hello, {nameAlice}!"10print(greetingHello, Alice!)1112# Multiple variables13message→ Alice is 42 years old = f"{nameAlice} is {age42} years old"14print(messageAlice is 42 years old)1516# Without f-string (for comparison)17old_way→ Hello, Alice! = "Hello, " + nameAlice + "!"18print("Old way:", old_wayHello, Alice!)1920# Expressions in f-strings21x→ 10 = 1022y→ 20 = 202324# Arithmetic25print(f"{x10} + {y20} = {x + y}")26print(f"{x10} * {y20} = {x * y}")2728# Comparison29print(f"{x10} < {y20} is {x < y}")3031# Function calls32text→ hello = "hello"33print(f"Uppercase: {texthello.upper()}")34print(f"Length: {len(texthello)}")3536# Different data types37name→ Bob = "Bob"38age→ 30 = 3039height→ 1.75 = 1.7540is_active→ True = True4142print(f"Name: {nameBob}")43print(f"Age: {age30}")44print(f"Height: {height1.75}m")45print(f"Active: {is_activeTrue}")4647# Multi-line f-strings48item→ Widget = "Widget"49price→ 19.99 = 19.9950quantity→ 5 = 55152description→ Product: Widget Price: $19.99 Quantity: 5 Total: $99.94999999999999 = f"""53Product: {itemWidget}54Price: ${price19.99}55Quantity: {quantity5}56Total: ${price19.99 * quantity5}57"""58print(description Product: Widget Price: $19.99 Quantity: 5 Total: $99.94999999999999 )outputHello, Alice! Alice is 42 years old Old way: Hello, Alice! 10 + 20 = 30 10 * 20 = 200 10 < 20 is True Uppercase: HELLO Length: 5 Name: Bob Age: 30 Height: 1.75m Active: True Product: Widget Price: $19.99 Quantity: 5 Total: $99.94999999999999
fstring_basics
Embedding variables and expressions with f-prefix and curly braces
Expressions in F-Strings
expressions.py
Replay: real traced execution (multi-file project)
# Complex expressions
# Method calls
text = "hello world"
print(f"Original: {text}")
print(f"Upper: {text.upper()}")
print(f"Title: {text.title()}")
print(f"Capitalized: {text.capitalize()}")
# List and dict access
fruits = ["apple", "banana", "cherry"]
person = {"name": "Alice", "age": 25}
print(f"\nFirst fruit: {fruits[0]}")
print(f"Last fruit: {fruits[-1]}")
print(f"Name: {person['name']}")
print(f"Age: {person['age']}")
# Conditional expressions
score = 85
print(f"Result: {score} ({'Pass' if score >= 60 else 'Fail'})")
age = 20
status = f"Status: {'Adult' if age >= 18 else 'Minor'}"
print(status)
# Calculations
price = 19.99
quantity = 5
tax_rate = 0.08
print(f"\nPrice: ${price:.2f}")
print(f"Quantity: {quantity}")
print(f"Subtotal: ${price * quantity:.2f}")
print(f"Tax: ${price * quantity * tax_rate:.2f}")
print(f"Total: ${price * quantity * (1 + tax_rate):.2f}")
# List comprehensions
numbers = [1, 2, 3, 4, 5]
print(f"\nNumbers: {numbers}")
print(f"Squares: {[x**2 for x in numbers]}")
print(f"Sum: {sum(numbers)}")
print(f"Average: {sum(numbers) / len(numbers):.2f}")
# String operations
word1 = "Hello"
word2 = "World"
print(f"\nConcatenated: {word1 + ' ' + word2}")
print(f"Repeated: {word1 * 3}")
print(f"Reversed: {word1[::-1]}")
# Type conversions
value = 42
print(f"\nInteger: {value}")
print(f"Float: {float(value)}")
print(f"String: {str(value)}")
print(f"Binary: {bin(value)}")
print(f"Hex: {hex(value)}")
text ← hello world, fruits ← ['apple', 'banana', 'cherry'], person ← {'name': 'Alice', 'age': 25}
4# Method calls5text→ hello world = "hello world"67print(f"Original: {texthello world}")8print(f"Upper: {texthello world.upper()}")9print(f"Title: {texthello world.title()}")10print(f"Capitalized: {texthello world.capitalize()}")1112# List and dict access13fruits→ ['apple', 'banana', 'cherry'] = ["apple", "banana", "cherry"]14person→ {'name': 'Alice', 'age': 25} = {"name": "Alice", "age": 25}1516print(f"\nFirst fruit: {fruits[0]apple}")17print(f"Last fruit: {fruits[-1]cherry}")18print(f"Name: {person['name']Alice}")19print(f"Age: {person['age']25}")2021# Conditional expressions22score→ 85 = 852324print(f"Result: {score85} ({'Pass' if score >= 60 else 'Fail'})")2526age→ 20 = 2027status→ Status: Adult = f"Status: {'Adult' if age20 >= 18 else 'Minor'}"28print(statusStatus: Adult)2930# Calculations31price→ 19.99 = 19.9932quantity→ 5 = 533tax_rate→ 0.08 = 0.083435print(f"\nPrice: ${price19.99:.2f}")36print(f"Quantity: {quantity5}")37print(f"Subtotal: ${price19.99 * quantity5:.2f}")38print(f"Tax: ${price19.99 * quantity5 * tax_rate0.08:.2f}")39print(f"Total: ${price19.99 * quantity5 * (1 + tax_rate0.08):.2f}")4041# List comprehensions42numbers→ [1, 2, 3, 4, 5] = [1, 2, 3, 4, 5]4344print(f"\nNumbers: {numbers[1, 2, 3, 4, 5]}")45print(f"Squares: {[x**2 for x in numbers[1, 2, 3, 4, 5]]}")46print(f"Sum: {sum(numbers[1, 2, 3, 4, 5])}")47print(f"Average: {sum(numbers[1, 2, 3, 4, 5]) / len(numbers):.2f}")4849# String operations50word1→ Hello = "Hello"51word2→ World = "World"5253print(f"\nConcatenated: {word1Hello + ' ' + word2World}")54print(f"Repeated: {word1Hello * 3}")55print(f"Reversed: {word1[::-1]olleH}")5657# Type conversions58value→ 42 = 425960print(f"\nInteger: {value42}")61print(f"Float: {float(value42)}")62print(f"String: {str(value42)}")63print(f"Binary: {bin(value42)}")64print(f"Hex: {hex(value42)}")outputOriginal: hello world Upper: HELLO WORLD Title: Hello World Capitalized: Hello world First fruit: apple Last fruit: cherry Name: Alice Age: 25 Result: 85 (Pass) Status: Adult Price: $19.99 Quantity: 5 Subtotal: $99.95 Tax: $8.00 Total: $107.95 Numbers: [1, 2, 3, 4, 5] Squares: [1, 4, 9, 16, 25] Sum: 15 Average: 3.00 Concatenated: Hello World Repeated: HelloHelloHello Reversed: olleH Integer: 42 Float: 42.0 String: 42 Binary: 0b101010 Hex: 0x2a
fstring_expressions
Using method calls, conditionals, and calculations inside f-strings
Format Specifiers
format_specs.py
Replay: real traced execution (multi-file project)
# Format specifiers
# Decimal places
pi = 3.14159265359
print(f"Default: {pi}")
print(f"2 decimals: {pi:.2f}")
print(f"4 decimals: {pi:.4f}")
print(f"0 decimals: {pi:.0f}")
# Width and alignment
name = "Alice"
short = "Hi"
# Minimum width
print(f"|{name:10}|") # Right align (default for numbers)
print(f"|{short:10}|")
# Left align with <
print(f"|{name:<10}|")
print(f"|{short:<10}|")
# Right align with >
print(f"|{name:>10}|")
print(f"|{short:>10}|")
# Center align with ^
print(f"|{name:^10}|")
print(f"|{short:^10}|")
# Numbers with width
value = 42
print(f"|{value:5}|") # Right align
print(f"|{value:<5}|") # Left align
print(f"|{value:>5}|") # Right align explicit
print(f"|{value:05}|") # Zero padding
# Thousands separator
large = 1234567890
price = 1234.56
print(f"With separator: {large:,}")
print(f"Price: ${price:,.2f}")
# Signs
positive = 42
negative = -42
print(f"Default positive: {positive}")
print(f"Always sign: {positive:+}")
print(f"Always sign negative: {negative:+}")
print(f"Space for positive: {positive: }")
# Percentages
ratio = 0.756
print(f"Decimal: {ratio}")
print(f"Percentage: {ratio:.1%}")
print(f"Percentage 2 decimals: {ratio:.2%}")
pi ← 3.14159265359, name ← Alice, short ← Hi, value ← 42, large ← 1234567890
4# Decimal places5pi→ 3.14159265359 = 3.1415926535967print(f"Default: {pi3.14159265359}")8print(f"2 decimals: {pi3.14159265359:.2f}")9print(f"4 decimals: {pi3.14159265359:.4f}")10print(f"0 decimals: {pi3.14159265359:.0f}")1112# Width and alignment13name→ Alice = "Alice"14short→ Hi = "Hi"1516# Minimum width17print(f"|{nameAlice:10}|") # Right align (default for numbers)18print(f"|{shortHi:10}|")1920# Left align with <21print(f"|{nameAlice:<10}|")22print(f"|{shortHi:<10}|")2324# Right align with >25print(f"|{nameAlice:>10}|")26print(f"|{shortHi:>10}|")2728# Center align with ^29print(f"|{nameAlice:^10}|")30print(f"|{shortHi:^10}|")3132# Numbers with width33value→ 42 = 423435print(f"|{value42:5}|") # Right align36print(f"|{value42:<5}|") # Left align37print(f"|{value42:>5}|") # Right align explicit38print(f"|{value42:05}|") # Zero padding3940# Thousands separator41large→ 1234567890 = 123456789042price→ 1234.56 = 1234.564344print(f"With separator: {large1234567890:,}")45print(f"Price: ${price1234.56:,.2f}")4647# Signs48positive→ 42 = 4249negative→ -42 = -425051print(f"Default positive: {positive42}")52print(f"Always sign: {positive42:+}")53print(f"Always sign negative: {negative-42:+}")54print(f"Space for positive: {positive42: }")5556# Percentages57ratio→ 0.756 = 0.7565859print(f"Decimal: {ratio0.756}")60print(f"Percentage: {ratio0.756:.1%}")61print(f"Percentage 2 decimals: {ratio0.756:.2%}")outputDefault: 3.14159265359 2 decimals: 3.14 4 decimals: 3.1416 0 decimals: 3 |Alice | |Hi | |Alice | |Hi | | Alice| | Hi| | Alice | | Hi | | 42| |42 | | 42| |00042| With separator: 1,234,567,890 Price: $1,234.56 Default positive: 42 Always sign: +42 Always sign negative: -42 Space for positive: 42 Decimal: 0.756 Percentage: 75.6% Percentage 2 decimals: 75.60%
format_specs
Controlling decimal places, width, alignment, and number formatting
Alignment
alignment.py
Replay: real traced execution (multi-file project)
# Alignment and padding
# Table formatting
print("Employee Table:")
print(f"{'Name':<10} {'Age':>5} {'Salary':>10}")
print("-" * 27)
employees = [
("Alice", 25, 75000),
("Bob", 30, 82000),
("Charlie", 35, 91000),
]
for name, age, salary in employees:
print(f"{name:<10} {age:>5} ${salary:>9,}")
# Padding with different characters
title = "Report"
print(f"\n{title:=^30}") # Center with = padding
print(f"{title:-^30}") # Center with - padding
print(f"{title:*^30}") # Center with * padding
# Right-aligned numbers
print("\nSales Report:")
print(f"{'Item':<15} {'Quantity':>10} {'Revenue':>12}")
print("-" * 40)
sales = [
("Widget A", 150, 15000.50),
("Widget B", 75, 7500.25),
("Widget C", 220, 22000.00),
]
for item, qty, revenue in sales:
print(f"{item:<15} {qty:>10,} ${revenue:>11,.2f}")
# Progress bar
def progress_bar(percent, width=30):
"""Create a text progress bar"""
filled = int(width * percent / 100)
bar = "█" * filled + "░" * (width - filled)
return f"[{bar}] {percent:>3}%"
print("\nProgress:")
for p in [0, 25, 50, 75, 100]:
print(progress_bar(p))
# Box drawing
def print_box(text, width=40):
"""Print text in a box"""
print("┌" + "─" * (width - 2) + "┐")
print(f"│{text:^{width - 2}}│")
print("└" + "─" * (width - 2) + "┘")
print()
print_box("Important Message")
print_box("Centered Text", 30)
employees ← [('Alice', 25, 75000), ('Bob', 30, 82000), ('Charlie', 35, 91000)]
4# Table formatting5print("Employee Table:")6print(f"{'Name':<10} {'Age':>5} {'Salary':>10}")7print("-" * 27)89employees→ [('Alice', 25, 75000), ('Bob', 30, 82000), ('Charlie', 35, 91000)] = [10 ("Alice", 25, 75000),11 ("Bob", 30, 82000),12 ("Charlie", 35, 91000),13]outputEmployee Table: Name Age Salary ---------------------------for name, age, salary in employees:
pass 1 of 315for nameAlice, age25, salary75000 in employees[('Alice', 25, 75000), ('Bob', 30, 82000), ('Charlie', 35, 91000)]:16 print(f"{nameAlice:<10} {age25:>5} ${salary75000:>9,}")outputAlice 25 $ 75,000All 3 passes — pass 1 is the card above pass nameagesalary1 Alice 25 75000 2 Bob 30 82000 3 Charlie 35 91000 title ← Report, sales ← [('Widget A', 150, 15000.5), ('Widget B', 75, 7500.25), ('Widget C', 220, 22000.0)]
18# Padding with different characters19title→ Report = "Report"2021print(f"\n{titleReport:=^30}") # Center with = padding22print(f"{titleReport:-^30}") # Center with - padding23print(f"{titleReport:*^30}") # Center with * padding2425# Right-aligned numbers26print("\nSales Report:")27print(f"{'Item':<15} {'Quantity':>10} {'Revenue':>12}")28print("-" * 40)2930sales→ [('Widget A', 150, 15000.5), ('Widget B', 75, 7500.25), ('Widget C', 220, 22000.0)] = [31 ("Widget A", 150, 15000.50),32 ("Widget B", 75, 7500.25),33 ("Widget C", 220, 22000.00),34]output ============Report============ ------------Report------------ ************Report************ Sales Report: Item Quantity Revenue ----------------------------------------for item, qty, revenue in sales:
pass 1 of 336for itemWidget A, qty150, revenue15000.5 in sales[('Widget A', 150, 15000.5), ('Widget B', 75, 7500.25), ('Widget C', 220, 22000.0)]:37 print(f"{itemWidget A:<15} {qty150:>10,} ${revenue15000.5:>11,.2f}")outputWidget A 150 $ 15,000.50All 3 passes — pass 1 is the card above pass itemqtyrevenue1 Widget A 150 15000.5 2 Widget B 75 7500.25 3 Widget C 220 22000.0 print(" Progress:")
47print("\nProgress:")48for p in [0, 25, 50, 75, 100]:output Progress:for p in [0, 25, 50, 75, 100]:
pass 1 of 547print("\nProgress:")48for p0 in [0, 25, 50, 75, 100]:49 print(progress_bar(p0))All 5 passes — pass 1 is the card above pass p1 0 2 25 3 50 4 75 5 100 filled ← 0, bar ← ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
pass 1 of 539# Progress bar40def progress_bar(percent0, width30=30):41 """Create a text progress bar"""42 filled→ 0 = int(width30 * percent0 / 100)43 bar→ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ = "█" * filled0 + "░" * (width30 - filled)44 return f"[{bar░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░}] {percent0:>3}%"All 5 passes — pass 1 is the card above pass percentfilledbar1 0 0 ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 2 25 7 ███████░░░░░░░░░░░░░░░░░░░░░░░ 3 50 15 ███████████████░░░░░░░░░░░░░░░ 4 75 22 ██████████████████████░░░░░░░░ 5 100 30 ██████████████████████████████ print(progress_bar(p))
48for p in [0, 25, 50, 75, 100]:49 print(progress_bar(p0))output[░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░] 0%print(progress_bar(p))
48for p in [0, 25, 50, 75, 100]:49 print(progress_bar(p25))output[███████░░░░░░░░░░░░░░░░░░░░░░░] 25%print(progress_bar(p))
48for p in [0, 25, 50, 75, 100]:49 print(progress_bar(p50))output[███████████████░░░░░░░░░░░░░░░] 50%print(progress_bar(p))
48for p in [0, 25, 50, 75, 100]:49 print(progress_bar(p75))output[██████████████████████░░░░░░░░] 75%print(progress_bar(p))
48for p in [0, 25, 50, 75, 100]:49 print(progress_bar(p100))output[██████████████████████████████] 100%print()
59print()60print_box("Important Message")61print_box("Centered Text", 30)def print_box(text, width=40):
pass 1 of 251# Box drawing52def print_box(textImportant Message, width40=40):53 """Print text in a box"""54 print("┌" + "─" * (width40 - 2) + "┐")55 print(f"│{textImportant Message:^{width40 - 2}}│")56 print("└" + "─" * (width40 - 2) + "┘")output┌──────────────────────────────────────┐ │ Important Message │ └──────────────────────────────────────┘print_box("Important Message")
59print()60print_box("Important Message")61print_box("Centered Text", 30)def print_box(text, width=40):
pass 2 of 251# Box drawing52def print_box(textCentered Text, width30=40):53 """Print text in a box"""54 print("┌" + "─" * (width30 - 2) + "┐")55 print(f"│{textCentered Text:^{width30 - 2}}│")56 print("└" + "─" * (width30 - 2) + "┘")output┌────────────────────────────┐ │ Centered Text │ └────────────────────────────┘print_box("Centered Text", 30)
60print_box("Important Message")61print_box("Centered Text", 30)
fstring_alignment
Left, right, and center alignment with fill characters
Debug Syntax
debug.py
Replay: real traced execution (multi-file project)
# Debug format (Python 3.8+)
# Debug syntax
x = 42
name = "Alice"
# Regular f-string
print(f"x is {x}")
# Debug format: shows variable name and value
print(f"{x=}")
print(f"{name=}")
# Debugging expressions
a = 10
b = 20
print(f"{a + b=}")
print(f"{a * b=}")
print(f"{a > b=}")
# Method calls in debug
text = "hello"
print(f"{text.upper()=}")
print(f"{len(text)=}")
print(f"{text[::-1]=}")
# Multiple variables
width = 10
height = 20
area = width * height
print(f"{width=}, {height=}, {area=}")
# Complex expressions
numbers = [1, 2, 3, 4, 5]
print(f"{sum(numbers)=}")
print(f"{max(numbers)=}")
print(f"{len(numbers)=}")
# Debugging calculations
price = 19.99
quantity = 5
tax_rate = 0.08
print(f"{price=:.2f}")
print(f"{quantity=}")
print(f"{price * quantity=:.2f}")
print(f"{price * quantity * tax_rate=:.2f}")
# Custom format with debug
value = 3.14159
print(f"{value=}")
print(f"{value=:.2f}")
print(f"{value=:.4f}")
x ← 42, name ← Alice, a ← 10, b ← 20, text ← hello, width ← 10
4# Debug syntax5x→ 42 = 426name→ Alice = "Alice"78# Regular f-string9print(f"x is {x42}")1011# Debug format: shows variable name and value12print(f"{x42=}")13print(f"{nameAlice=}")1415# Debugging expressions16a→ 10 = 1017b→ 20 = 201819print(f"{a10 + b20=}")20print(f"{a10 * b20=}")21print(f"{a10 > b20=}")2223# Method calls in debug24text→ hello = "hello"2526print(f"{texthello.upper()=}")27print(f"{len(texthello)=}")28print(f"{text[::-1]olleh=}")2930# Multiple variables31width→ 10 = 1032height→ 20 = 2033area→ 200 = width10 * height203435print(f"{width10=}, {height20=}, {area200=}")3637# Complex expressions38numbers→ [1, 2, 3, 4, 5] = [1, 2, 3, 4, 5]3940print(f"{sum(numbers[1, 2, 3, 4, 5])=}")41print(f"{max(numbers[1, 2, 3, 4, 5])=}")42print(f"{len(numbers[1, 2, 3, 4, 5])=}")4344# Debugging calculations45price→ 19.99 = 19.9946quantity→ 5 = 547tax_rate→ 0.08 = 0.084849print(f"{price19.99=:.2f}")50print(f"{quantity5=}")51print(f"{price19.99 * quantity5=:.2f}")52print(f"{price19.99 * quantity5 * tax_rate0.08=:.2f}")5354# Custom format with debug55value→ 3.14159 = 3.141595657print(f"{value3.14159=}")58print(f"{value3.14159=:.2f}")59print(f"{value3.14159=:.4f}")outputx is 42 x=42 name='Alice' a + b=30 a * b=200 a > b=False text.upper()='HELLO' len(text)=5 text[::-1]='olleh' width=10, height=20, area=200 sum(numbers)=15 max(numbers)=5 len(numbers)=5 price=19.99 quantity=5 price * quantity=99.95 price * quantity * tax_rate=8.00 value=3.14159 value=3.14 value=3.1416
debug_syntax
Using f'{variable=}' syntax for debugging output
Advantages
- Readable: Expression directly in string
- Concise: Less code than .format()
- Fast: Evaluated at runtime, optimized
- Powerful: Full Python expressions
Python 3.6+
F-strings require Python 3.6 or later. For older versions, use:
"text {}".format(value)"text %s" % value
Exercise: practical.py
Create invoice, log, and statistics formatters using f-strings