In Python, output formatting allows you to display data in a clean, organized, and readable manner. Below are the main methods and techniques for formatting output in Python:
1. Using f-strings (Python 3.6+)
F-strings are a concise and efficient way to format strings. They use curly braces {}
to embed expressions directly in the string.
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
Output:
My name is Alice and I am 25 years old.
You can also format numbers:
pi = 3.14159
print(f"The value of pi is approximately {pi:.2f}.")
Output:
The value of pi is approximately 3.14.
2. Using str.format()
The str.format()
method allows you to format strings by placing placeholders {}
in the text.
print("My name is {} and I am {} years old.".format(name, age))
Output:
My name is Alice and I am 25 years old.
With positional or keyword arguments:
print("Hello, {0}! You are {1} years old.".format("Bob", 30))
print("Hello, {name}! You are {age} years old.".format(name="Carol", age=27))
3. Using the %
Operator
This is an older method for string formatting using placeholders like %s
, %d
, or %f
.
print("My name is %s and I am %d years old." % (name, age))
Output:
My name is Alice and I am 25 years old.
For floating-point precision:
print("The value of pi is approximately %.2f." % pi)
4. Using format()
for Alignment and Padding
You can control alignment and width in output:
print("{:<10} {:>10}".format("Left", "Right")) # Left and right alignment
print("{:^10}".format("Center")) # Center alignment
Output:
Left Right
Center
5. Using tabulate
for Tabular Data (Optional Library)
For structured tabular output, the tabulate
library is helpful.
pip install tabulate
from tabulate import tabulate
data = [["Alice", 25], ["Bob", 30], ["Carol", 27]]
print(tabulate(data, headers=["Name", "Age"], tablefmt="grid"))
6. Using pprint
for Pretty-Printing Data Structures
The pprint
module is useful for printing nested data structures.
import pprint
data = {"name": "Alice", "age": 25, "skills": ["Python", "JavaScript"]}
pprint.pprint(data)
Choose the method that best fits your task! For most modern use cases, f-strings are the recommended approach due to their clarity and performance.