🎨 Formatting Strings
Python offers multiple ways to format strings, with f-strings being the most modern and readable approach. String formatting is essential for creating dynamic output and combining text with variables.
# Basic string formatting
name = "Alice"
age = 25
message = f"{name} is {age} years old"
print(message)
🎯 String Formatting Methods
Python provides several methods for string formatting, each with its own use cases.
F-String Examples
# F-string formatting examples
name = "Bob"
age = 30
score = 95.5
# Basic variable insertion
print(f"Name: {name}")
# Expressions
print(f"Next year's age: {age + 1}")
# Formatting numbers
print(f"Score: {score:.1f}%")
# Multiple variables
print(f"{name} is {age} years old and scored {score:.1f}%")
Format Method Examples
# Format method examples
name = "Charlie"
age = 35
# Positional arguments
print("{} is {} years old".format(name, age))
# Named arguments
print("{n} is {a} years old".format(n=name, a=age))
# Format specifiers
print("Age: {:.1f}".format(35.0))
🔍 Format Specifiers
Format specifiers control how values are displayed in formatted strings.
# Format specifier examples
number = 123.456789
# Different number formats
print(f"Default: {number}")
print(f"2 decimal places: {number:.2f}")
print(f"Scientific: {number:e}")
print(f"Percentage: {number:.1%}")
# String formatting
text = "Python"
print(f"Left aligned: {text:<10}")
print(f"Right aligned: {text:>10}")
print(f"Centered: {text:^10}")
🎨 Common Use Cases
Here are some practical examples of string formatting.
# 1. Creating a table
def print_table(data):
for name, score in data:
print(f"{name:<10} | {score:>5.1f}%")
# 2. Formatting currency
def format_price(amount):
return f"${amount:,.2f}"
# 3. Creating a progress bar
def progress_bar(current, total):
percentage = current / total * 100
return f"[{'=' * int(percentage/10)}{' ' * (10-int(percentage/10))}] {percentage:.1f}%"
# Test the functions
scores = [("Alice", 95.5), ("Bob", 88.0), ("Charlie", 92.5)]
print_table(scores)
print(format_price(1234.56))
print(progress_bar(7, 10))
📝 Quick Practice
Let's practice string formatting with a real-world scenario!
Hands-on Exercise
Create a function to format a receipt.
python
# Receipt Formatting Practice
def format_receipt(items, tax_rate=0.1):
# TODO: Implement receipt formatting
# 1. Format each item with name, quantity, and price
# 2. Calculate subtotal, tax, and total
# 3. Format the final receipt with proper alignment
# Example items: [("Apple", 2, 0.50), ("Banana", 3, 0.75)]
return ""
# Test the function
items = [("Apple", 2, 0.50), ("Banana", 3, 0.75), ("Orange", 1, 1.25)]
print(format_receipt(items))
Solution and Explanation 💡
Click to see the solution
# Receipt Formatting Solution
def format_receipt(items, tax_rate=0.1):
# Calculate totals
subtotal = sum(quantity * price for _, quantity, price in items)
tax = subtotal * tax_rate
total = subtotal + tax
# Format receipt
receipt = "RECEIPT\n" + "=" * 30 + "\n"
# Format items
for name, quantity, price in items:
item_total = quantity * price
receipt += f"{name:<10} {quantity:>2} x ${price:>5.2f} = ${item_total:>6.2f}\n"
# Format totals
receipt += "-" * 30 + "\n"
receipt += f"Subtotal: ${subtotal:>20.2f}\n"
receipt += f"Tax: ${tax:>23.2f}\n"
receipt += f"Total: ${total:>22.2f}\n"
return receipt
# Test the function
items = [("Apple", 2, 0.50), ("Banana", 3, 0.75), ("Orange", 1, 1.25)]
print(format_receipt(items))
Key Learning Points:
- 📌 Used f-strings with format specifiers
- 📌 Used alignment operators (
<
,>
,^
) - 📌 Used decimal formatting (
.2f
) - 📌 Used string multiplication for lines
🎯 Key Takeaways
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.