
Python
String formatting is how you combine variables with text to create readable output. The modern way to do this in Python is with f-strings (formatted string literals), which let you insert variables directly into strings using curly braces. F-strings are cleaner, faster, and more readable than older methods, making them the preferred approach for formatting text.
F-strings (formatted string literals) let you embed expressions directly in strings using curly braces {}. You create an f-string by putting the letter f before the opening quote, then use {variable} to insert values. This is much cleaner than concatenating strings with + and more readable than older formatting methods.
# Old way (avoid)
name = "Alice"
age = 25
message = "My name is " + name + " and I am " + str(age)
# New way (use this!)
message = f"My name is {name} and I am {age}"
print(message) # Output: My name is Alice and I am 25Inside the curly braces of an f-string, you can put any variable name and Python will insert its value. You can use multiple variables in one string, and they'll be replaced with their current values. This makes it easy to create dynamic text that changes based on your data.
# Multiple variables in f-strings
first_name = "John"
last_name = "Doe"
age = 30
city = "New York"
# Simple insertion
greeting = f"Hello, {first_name} {last_name}!"
# Multiple variables
profile = f"I'm {first_name}, {age} years old, from {city}"
# With calculations
birth_year = 2024 - age
bio = f"{first_name} was born around {birth_year}"
print(greeting)
print(profile)
print(bio)Inside f-strings, you can format numbers to control decimal places, add thousand separators, or format as percentages. Use a colon after the variable name, followed by format specifiers like .2f (2 decimal places) or :, (comma separator). This makes it easy to display money, percentages, and other numbers professionally.
# Format decimal places
price = 19.99654
print(f"Price: ${price:.2f}") # Output: Price: $19.99
# Thousand separator
big_number = 1000000
print(f"Number: {big_number:,}") # Output: Number: 1,000,000
# Combine both
total = 1234.5678
print(f"Total: ${total:,.2f}") # Output: Total: $1,234.57
# Percentages
percentage = 0.856
print(f"Score: {percentage:.1%}") # Output: Score: 85.6%Inside the curly braces, you can put more than just variable names — you can put entire expressions! Python will evaluate the expression and insert the result. This is useful for quick calculations without creating separate variables.
# Simple calculations
x = 10
y = 3
print(f"{x} + {y} = {x + y}") # Output: 10 + 3 = 13
print(f"{x} * {y} = {x * y}") # Output: 10 * 3 = 30
# Function calls
text = "hello"
print(f"Uppercase: {text.upper()}") # Output: Uppercase: HELLO
print(f"Length: {len(text)}") # Output: Length: 5
# Conditional expressions
age = 20
status = f"I am {'an adult' if age >= 18 else 'a minor'}"
print(status) # Output: I am an adultproduct = "Laptop"
price = 999.99
quantity = 2
tax_rate = 0.08
subtotal = price * quantity
tax = subtotal * tax_rate
total = subtotal + tax
print(f"""
{'='*40}
Product Report
{'='*40}
Product: {product}
Price: ${price:.2f}
Quantity: {quantity}
Subtotal: ${subtotal:,.2f}
Tax (8%): ${tax:,.2f}
Total: ${total:,.2f}
{'='*40}
""")name = "Sarah"
age = 28
height = 5.7
gpa = 3.85
print(f"""
User Profile:
- Name: {name}
- Age: {age} years old
- Height: {height} feet
- GPA: {gpa:.2f}
""")subject = "Python"
score = 92.5
max_score = 100
percentage = (score / max_score) * 100
print(f"""
Subject: {subject}
Score: {score}/{max_score}
Percentage: {percentage:.1f}%
Grade: {'A' if percentage >= 90 else 'B' if percentage >= 80 else 'C'}
""")| Feature | Example | Result |
|---|---|---|
| Basic | f"{name}" | Inserts variable |
| Calculation | f"{x + y}" | 13 (evaluates expression) |
| Decimal Places | f"{3.14159:.2f}" | 3.14 |
| Thousands Sep | f"{1000000:,}" | 1,000,000 |
| Percentage | f"{0.85:.0%}" | 85% |
| Method Call | f"{text.upper()}" | Calls method |
You've learned about numbers, strings, and formatting. Now let's explore booleans and the None type — essential for decision-making!
Ready to practice? Try challenges or take the quiz
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward