Output formatting means displaying information in a neat, organized, and readable way.
For example:
Instead of this messy output:
Danny 25 95.5
We want something cleaner like:
Name: Danny Age: 25 Score: 95.5
๐ 1. Basic Output Using print()
print("Hello World")
You can also print variables:
name = "Danny" print(name)
๐ 2. Printing Multiple Values
name = "Danny" age = 25 print(name, age)
By default, Python separates them with a space.
๐ 3. Using sep (Separator)
The sep parameter controls how items are separated.
print("Python", "Java", "C++", sep=" | ")
Output:
Python | Java | C++
๐ 4. Using end (Line Ending)
By default, print() ends with a new line (\n).
You can change it:
print("Hello", end=" ")
print("World")
Output:
Hello World
๐ 5. f-Strings (Best & Modern Method โ )
This is the easiest and most recommended method.
name = "Danny"
age = 25
print(f"My name is {name} and I am {age} years old.")
Why f-strings?
- Easy to read
- Fast
- Clean
- Modern (Python 3.6+)
๐ 6. Controlling Decimal Places
price = 19.9876
print(f"Price: {price:.2f}")
Output:
Price: 19.99
.2f means:
- 2 decimal places
- f = float
๐ 7. Setting Width (Alignment)
You can control spacing.
name = "Danny"
print(f"{name:10}")
This means:
- Reserve 10 spaces
Alignment Options
| Format | Meaning | Example |
|--------|----------|----------|
| :<10 | Left align | f"{name:<10}" |
| :>10 | Right align | f"{name:>10}" |
| :^10 | Center align | f"{name:^10}" |
Example:
print(f"{'Python':<10}")
print(f"{'Python':>10}")
print(f"{'Python':^10}")
๐ 8. Formatting Numbers
Add Commas (for thousands)
number = 1000000
print(f"{number:,}")
Output:
1,000,000
Percentage Format
score = 0.85
print(f"{score:.0%}")
Output:
85%
๐ 9. Using format() Method
Older but still useful.
name = "Danny"
age = 25
print("My name is {} and I am {}".format(name, age))
You can also number them:
print("My name is {0} and I am {1}".format(name, age))
๐ 10. Old % Formatting (Very Old Method)
name = "Danny"
age = 25
print("My name is %s and I am %d" % (name, age))
๐ Comparison of Formatting Methods
| Method | Easy to Read | Modern | Recommended | |--------|--------------|----------|--------------| | f-string | Yes | Yes | โ Best | | format() | Medium | Yes | โ Good | | % operator | Harder | No | โ Old |
๐ 11. Escape Characters in Output
| Escape | Meaning | |--------|----------| | \n | New line | | \t | Tab space | | \\ | Backslash | | \" | Double quote | | \' | Single quote |
Example:
print("Name:\tDanny")
Output:
Name: Danny
๐ 12. Printing a Simple Table
You can format output like a table:
name = "Danny"
age = 25
score = 92.456
print(f"{'Name':<10}{'Age':<5}{'Score':<10}")
print(f"{name:<10}{age:<5}{score:<10.2f}")
Output:
Name Age Score Danny 25 92.46
๐ 13. Real-Life Example (Student Report)
name = "Danny"
math = 85
english = 90
average = (math + english) / 2
print("----- REPORT -----")
print(f"Name: {name}")
print(f"Math: {math}")
print(f"English: {english}")
print(f"Average: {average:.2f}")