Python – Output Formatting

Introduction

In Python, output formatting refers to the way data is presented when printed or logged. Proper formatting makes information more understandable and actionable. Python provides several ways to format strings effectively, ranging from old-style formatting to the newer f-string approach.

Formatting Output using String Modulo Operator (%)

The string modulo operator (%) is one of the oldest ways to format strings in Python. It allows you to embed values within a string by placing format specifiers in the string. Each specifier starts with a % and ends with a character that represents the type of value being formatted.

print("Apples: %2d, Price: %5.2f" % (3, 1.245)) 
print("Total items: %3d, Sold: %2d" % (150, 75))   # print integer value
print("%7.3o" % (31))   # print octal value
print("%10.3E" % (123.45678))   # print exponential value
        

Output:

Apples:  3, Price:  1.25
Total items: 150, Sold: 75
    037
 1.235E+02

Formatting Output using The format() Method

The format() method was introduced in Python 2.6 to enhance string formatting capabilities. This method allows for a more flexible way to handle string interpolation using curly braces {} as placeholders for substituting values into a string.

Basic Positional Formatting

print("I enjoy {0} during \"{1}!\"".format("Baking", "Weekend"))
print("{0} and Snacks".format("Baking"))
print("Snacks and {0}".format("Baking"))
        

Output:

I enjoy Baking during "Weekend!"
Baking and Snacks
Snacks and Baking

Advanced Usage with Positional and Named Parameters

template = "Main dish is {0}, {1} and {other}."
print(template.format("Pasta", "Salad", other="Bread"))
print("Items: {0:2d}, Price: {1:8.2f}".format(3, 12.349))
print("Second item: {1:3d}, first one: {0:8.2f}".format(22.50, 5))
print("Items: {a:5d}, Price: {p:8.2f}".format(a=300, p=15.678))
        

Output:

Main dish is Pasta, Salad and Bread.
Items:  3, Price:   12.35
Second item:  5, first one:    22.50
Items:   300, Price:    15.68

Formatting Output using String Methods

Python’s string methods such as str.center(), str.ljust(), and str.rjust() provide straightforward ways to format strings by aligning them within a specified width.

s = "I love programming"
print("Center aligned: ")
print(s.center(40, '*'))
print("Left aligned: ")
print(s.ljust(40, '-'))
print("Right aligned: ")
print(s.rjust(40, '-'))
        

Output:

Center aligned: 
********I love programming********
Left aligned: 
I love programming------------------
Right aligned: 
------------------I love programming

Conclusion

In this post, we explored various methods for formatting output in Python, including the old-style string modulo operator, the format() method, and string methods for alignment. Understanding these formatting techniques enhances the clarity and readability of output, making it easier to present and log information effectively.