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
print()
print("Hello World")
You can also print variables:
name = "Danny" print(name)
name = "Danny" age = 25 print(name, age)
By default, Python separates them with a space.
sep (Separator)The sep parameter controls how items are separated.
print("Python", "Java", "C++", sep=" | ")
Output:
Python | Java | C++
end (Line Ending)By default, print() ends with a new line (\n).
You can change it:
print("Hello", end=" ")
print("World")
Output:
Hello World
This is the easiest and most recommended method.
name = "Danny"
age = 25
print(f"My name is {name} and I am {age} years old.")
price = 19.9876
print(f"Price: {price:.2f}")
Output:
Price: 19.99
.2f means:
You can control spacing.
name = "Danny"
print(f"{name:10}")
This means:
| 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}")
number = 1000000
print(f"{number:,}")
Output:
1,000,000
score = 0.85
print(f"{score:.0%}")
Output:
85%
format() MethodOlder 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))
name = "Danny"
age = 25
print("My name is %s and I am %d" % (name, age))
| Method | Easy to Read | Modern | Recommended | |--------|--------------|----------|--------------| | f-string | Yes | Yes | ✅ Best | | format() | Medium | Yes | ✔ Good | | % operator | Harder | No | ❌ Old |
| Escape | Meaning | |--------|----------| | \n | New line | | \t | Tab space | | \\ | Backslash | | \" | Double quote | | \' | Single quote |
Example:
print("Name:\tDanny")
Output:
Name: Danny
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
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}")