5.3. Formatting output
Table of Contents
Why Formatting Output Matters
When you print things in Python, the default output is often not very pretty:
price = 4.5
print("Price:", price)Output:
Price: 4.5For simple scripts this is fine, but for user‑facing or slightly larger programs you usually want:
- Numbers aligned in columns
- A fixed number of decimal places
- Clear labels and units
- Nicely structured sentences
This is what formatting output is about: controlling how values appear when you show them to the user.
In this chapter, you’ll learn several easy ways to format text and values using:
print()options- f‑strings (formatted string literals)
- The
format()method (briefly)
You’ll mainly use these tools together with what you already know about user input and basic data types.
Basic `print()` Formatting
Using `sep` to control separators
By default, print() separates items with a space:
print("Total:", 10, "items")
# Total: 10 items
You can change that using the sep (separator) argument:
print("A", "B", "C", sep="-")
# A-B-C
print("2025", "12", "31", sep="/")
# 2025/12/31
print("apple", "banana", "cherry", sep=", ")
# apple, banana, cherryThis is useful when you want to join multiple values with a specific character or string.
Using `end` to control line endings
By default, print() ends with a newline (\n), which moves the cursor to the next line:
print("Hello")
print("World")
# Hello
# World
You can change the ending using end:
print("Loading", end="...")
print("done")
# Loading...doneAnother common use: staying on the same line when printing step-by-step progress.
String Formatting with f-strings (Recommended)
The most convenient and modern way to format output in Python is using f-strings (formatted string literals).
You put an f in front of a string, and then you can insert variables inside {}.
name = "Alex"
age = 25
print(f"Hello, {name}. You are {age} years old.")
# Hello, Alex. You are 25 years old.You can combine text and any kind of value:
price = 4.5
quantity = 3
total = price * quantity
print(f"Price: {price}, Quantity: {quantity}, Total: {total}")
# Price: 4.5, Quantity: 3, Total: 13.5
This is easier to read than using + or commas to build strings.
Controlling Number of Decimal Places
When working with float numbers, you often want a fixed number of decimal places (for example, for money).
With f-strings, you can specify formatting inside the {} using a colon : followed by a format specification.
Fixed decimal places with `.2f`
:.2f means: show as a floating-point number with 2 digits after the decimal point.
price = 4.5
tax_rate = 0.075
tax = price * tax_rate
total = price + tax
print(f"Price: {price:.2f}")
print(f"Tax: {tax:.2f}")
print(f"Total: {total:.2f}")Example output:
Price: 4.50
Tax: 0.34
Total: 4.84Other examples:
:.1f→ 1 decimal place:.3f→ 3 decimal places
number = 3.14159265
print(f"{number:.1f}") # 3.1
print(f"{number:.3f}") # 3.142Aligning and Padding Output
If you are printing tables or columns, alignment matters.
Format specs can also control width and alignment.
General pattern inside {}:
{value:width}→ minimum width{value:>width}→ right aligned{value:<width}→ left aligned{value:^width}→ centered
Aligning text
item1 = "Apples"
item2 = "Bananas"
item3 = "Kiwi"
print(f"{item1:<10} - good")
print(f"{item2:<10} - good")
print(f"{item3:<10} - good")Output:
Apples - good
Bananas - good
Kiwi - good
Here, <10 means: left-align in a field of width 10 characters.
Aligning numbers in columns
a = 3.5
b = 12.0
c = 123.456
print(f"{'Value':>10}")
print(f"{a:>10.2f}")
print(f"{b:>10.2f}")
print(f"{c:>10.2f}")Example output:
Value
3.50
12.00
123.46>10.2fmeans:- total width at least 10 characters
- right aligned
- 2 decimal places
Adding Units, Labels, and Newlines
Units and labels
Formatting is often about making meaning clear:
temperature = 21.678
print(f"Temperature: {temperature:.1f} °C")
# Temperature: 21.7 °C
speed = 58.3
print(f"Speed: {speed} km/h")
# Speed: 58.3 km/hNewlines `\n`
You can use \n inside strings to start a new line:
name = "Alex"
score = 95
message = f"Student: {name}\nScore: {score}"
print(message)Output:
Student: Alex
Score: 95You can combine this with formatting:
price = 9.99
quantity = 3
total = price * quantity
receipt = (
f"Receipt\n"
f"--------\n"
f"Price: ${price:.2f}\n"
f"Quantity: {quantity}\n"
f"Total: ${total:.2f}"
)
print(receipt)Formatting Percentages
Sometimes you want to show a fraction as a percentage.
Basic way:
ratio = 0.237
percent = ratio * 100
print(f"Ratio: {ratio} -> {percent:.1f}%")
# Ratio: 0.237 -> 23.7%
More compact with % format spec: :.1% means percentage with 1 decimal place:
ratio = 0.237
print(f"Completion: {ratio:.1%}")
# Completion: 23.7%
Here Python multiplies by 100 and adds the % sign for you.
A Quick Look at `str.format()` (Alternative)
Before f-strings were added, Python used the format() method. You may still see it in older code.
Basic usage:
name = "Alex"
age = 25
print("Hello, {}. You are {} years old.".format(name, age))With positions:
print("Name: {0}, Age: {1}".format(name, age))With names:
print("Name: {n}, Age: {a}".format(n=name, a=age))
You can use the same format specs inside the {}:
price = 4.5
print("Price: {:.2f}".format(price)) # Price: 4.50
For new code, f-strings are usually simpler and clearer, but understanding format() helps when reading others’ programs.
Common Beginner Mistakes with Formatting
1. Mixing `+` with non-strings
This will cause an error:
age = 20
# print("You are " + age + " years old") # TypeErrorUse one of these instead:
- Use commas:
print("You are", age, "years old")- Or use an f-string:
print(f"You are {age} years old")2. Forgetting `f` in f-strings
name = "Alex"
# print("Hello, {name}") # Prints: Hello, {name}
print(f"Hello, {name}") # Correct: Hello, Alex3. Too many or too few format placeholders
name = "Alex"
age = 25
# print("Name: {}, Age: {}, City: {}".format(name, age)) # Error
You must have the same number of {} as values you pass to format().
Putting It All Together: Small Examples
Example 1: Simple receipt
item = "Notebook"
price = 2.5
quantity = 4
total = price * quantity
print("Receipt")
print("--------")
print(f"Item: {item}")
print(f"Price: ${price:.2f}")
print(f"Quantity: {quantity}")
print(f"Total: ${total:.2f}")Example 2: Neatly formatted table
print(f"{'Name':<10} {'Age':>3} {'Score':>6}")
print("-" * 21)
print(f"{'Alex':<10} {25:>3} {93.5:>6.1f}")
print(f"{'Sam':<10} {8:>3} {88.0:>6.1f}")
print(f"{'Jordan':<10} {31:>3} {77.25:>6.1f}")Possible output:
Name Age Score
---------------------
Alex 25 93.5
Sam 8 88.0
Jordan 31 77.3Practice Ideas
Try writing small programs that:
- Ask the user for their name and age, then print a nicely formatted sentence using an f-string.
- Ask for three product prices and print them in a right‑aligned column with 2 decimal places.
- Ask the user for a total number of questions and number of correct answers, then print their score as a percentage with 1 decimal place.
In each case, focus on how the output looks, not just on getting any output.
Views: 0
Where to Move
Move chapter:
- ☰ 1. Chapter 1: What Is Programming?
- ☰ 1.1. What is a computer program?
- ☰ 1.2. What is Python?
- ☰ 1.3. Where is Python used?
- ☰ 1.4. How programming helps solve problems
- ☰ 1.5. Your first Python program
-
- ☰ 2. Chapter 2: Setting Up Python
- ☰ 2.1. Installing Python (Windows / macOS / Linux)
- ☰ 2.2. Using Python in the terminal
- ☰ 2.3. Using an IDE (IDLE / VS Code)
- ☰ 2.4. Running Python scripts
- ☰ 2.5. Python interactive mode
-
- ☰ 3. Chapter 3: Variables and Data Types
- ☰ 3.1. What is a variable?
- ☰ 3.2. Creating variables
- ☰ 3.3. Numbers
- ☰ 3.4. Test
- ☰ 3.5. Boolean values
- ☰ 3.6. Type checking
-
- ☰ 4. Chapter 4: Basic Operations
- ☰ 4.1. Arithmetic operations
- ☰ 4.2. Working with numbers
- ☰ 4.3. String operations
- ☰ 4.4. Combining text and variables
- ☰ 4.5. Comments in Python
-
- ☰ 5. Chapter 5: User Input and Output
- ☰ 5.1. Getting input from the user
- ☰ 5.2. Converting input to numbers
- ☰ 5.3. Formatting output
- ☰ 5.4. Writing interactive programs
-
- ☰ 6. Chapter 6: Conditions
- ☰ 6.1. Comparison operators
- ☰ 6.2. Logical operators
- ☰ 6.3. if, elif, else
- ☰ 6.4. Nested conditions
- ☰ 6.5. Common beginner mistakes
-
- ☰ 7. Chapter 7: Loops
- ☰ 7.1. Why loops are useful
- ☰ 7.2. for loops
- ☰ 7.3. while loops
- ☰ 7.4. Loop counters
- ☰ 7.5. break and continue
- ☰ 7.6. Loop exercises
-
- ☰ 8. Chapter 8: Data Collections
- ☰ 8.1. Lists
- ☰ 8.2. Tuples
- ☰ 8.3. Dictionaries
- ☰ 8.4. Sets (basics)
- ☰ 8.5. Choosing the right data structure
-
- ☰ 9. Chapter 9: Functions
- ☰ 9.1. Why functions matter
- ☰ 9.2. Defining functions
- ☰ 9.3. Parameters and arguments
- ☰ 9.4. Return values
- ☰ 9.5. Scope (local vs global)
- ☰ 9.6. Reusing code
-
- ☰ 10. Chapter 10: Working with Files
- ☰ 10.1. What is a file?
- ☰ 10.2. Reading text files
- ☰ 10.3. Writing and appending files
- ☰ 10.4. File paths
- ☰ 10.5. Simple file-based programs
-
- ☰ 11. Chapter 11: Errors and Debugging
- ☰ 11.1. Types of errors
- ☰ 11.2. Reading error messages
- ☰ 11.3. Common beginner errors
- ☰ 11.4. try and except
- ☰ 11.5. Debugging strategies
-
- ☰ 12. Chapter 12: Using Python Libraries
- ☰ 12.1. What is a library?
- ☰ 12.2. Importing modules
- ☰ 12.3. Standard libraries
- ☰ 12.3.1. math
- ☰ 12.3.2. random
- ☰ 12.3.3. datetime
-
- ☰ 12.4. Installing external libraries with pip
-
- ☰ 13. Chapter 13: Object-Oriented Programming
- ☰ 13.1. What is object-oriented programming?
- ☰ 13.2. Classes and objects
- ☰ 13.3. The `__init__` method
- ☰ 13.4. Attributes and methods
- ☰ 13.5. Encapsulation
- ☰ 13.6. Inheritance (basics)
- ☰ 13.7. Simple OOP examples
-
- ☰ 14. Chapter 14: Automation with Python
- ☰ 14.1. What is automation?
- ☰ 14.2. Automating simple tasks
- ☰ 14.3. Working with files and folders
- ☰ 14.4. Automating text processing
- ☰ 14.5. Scheduling scripts
- ☰ 14.6. Practical automation examples
-
- ☰ 15. Chapter 15: Web Development with Python
- ☰ 15.1. How the web works (basic overview)
- ☰ 15.2. Introduction to Flask
- ☰ 15.3. Creating a simple web server
- ☰ 15.4. Routing and templates
- ☰ 15.5. Handling user input (forms)
- ☰ 15.6. Very basic APIs
-
- ☰ 16. Chapter 16: Data Science with Python
- ☰ 16.1. What is data science?
- ☰ 16.2. Working with data
- ☰ 16.3. Introduction to NumPy
- ☰ 16.4. Introduction to pandas
- ☰ 16.5. Data visualization with matplotlib
- ☰ 16.6. Simple data analysis examples
-
- ☰ 17. Chapter 17: Mini Projects
- ☰ 17.1. Number guessing game
- ☰ 17.2. Simple calculator
- ☰ 17.3. To-do list
- ☰ 17.4. Password generator
- ☰ 17.5. Quiz application
- ☰ 17.6. Small web or data project
-
- ☰ 18. Chapter 18: Next Steps
- ☰ 18.1. How to practice Python
- ☰ 18.2. Writing clean and readable code
- ☰ 18.3. Choosing a specialization
- ☰ 18.3.1. Web development
- ☰ 18.3.2. Data science
- ☰ 18.3.3. Automation
- ☰ 18.3.4. Software development
-
- ☰ 18.4. Learning resources and communities
-
- ☰ 19. Appendix
- ☰ 19.1. Python syntax cheat sheet
- ☰ 19.2. Common errors and solutions
- ☰ 19.3. Glossary of terms
-
Comments
Please login to add a comment.
Don't have an account? Register now!