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.
Debug Syntax
basics.py
# Basic f-strings
# Simple variable embedding
name =
age =
# 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 =
age =
# 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 =
age =
# 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 =
age =
# 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 =
age =
# 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 =
age =
# 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 =
age =
# 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 =
age =
# 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 =
age =
# 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)
expressions.py
# 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)}")
format_specs.py
# 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%}")
alignment.py
# 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)
debug.py
# 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}")
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
fstring_basics
Embedding variables and expressions with f-prefix and curly braces
fstring_expressions
Using method calls, conditionals, and calculations inside f-strings
format_specs
Controlling decimal places, width, alignment, and number formatting
fstring_alignment
Left, right, and center alignment with fill characters
debug_syntax
Using f'{variable=}' syntax for debugging output
Exercise: practical.py
Create invoice, log, and statistics formatters using f-strings