Python – Output Formatting
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.
# string modulo operator(%)
print("Geeks : %2d, Portal : %5.2f" % (1, 05.333))
print("Total students : %3d, Boys : %2d" % (240, 120)) # print integer value
print("%7.3o" % (25)) # print octal value
print("%10.3E" % (356.08977)) # print exponential value
Output
Geeks : 1, Portal : 5.33 Total students : 240, Boys : 120 031 3.561E+02
.png)
Output Formatting using Modulo Operator
There are several ways to format output using String Method in Python.
Table of Content
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 by using curly braces {} as placeholders for substituting values into a string. It supports both positional and named arguments, making it versatile for various formatting needs. For Example –
Example 1: Basic positional formatting demonstrates how values are substituted based on their order:
# Positional formatting with format() method
# Using indexed placeholders for string formatting
print("I love {0} for \"{1}!\"".format("Geeks", "Geeks"))
# {0} is replaced by the first argument 'Geeks'
print("{0} and Portal".format("Geeks"))
# Formatting with placeholders, {0} replaced by 'Geeks'
print("Portal and {0}".format("Geeks"))
Output
I love Geeks for "Geeks!" Geeks and Portal Portal and Geeks
In this example, {0} and {1} refer to the first and second argument provided to format(), respectively.
The following diagram with an example usage depicts how the format method works for positional parameters:
.png)
Output Formatting using Format method
Advanced Usage with Positional and Named Parameters
The format() method also supports detailed formatting options such as setting widths, alignment, number formatting and more, which can be extremely useful for creating tabulated data or reports.
Example 2: Here’s how positional parameters along with a named argument are used to format numbers and text precisely:
# Advanced formatting with positional and named arguments
# Mixing positional and named arguments
template = "Number one portal is {0}, {1} and {other}."
print(template.format("Geeks", "For", other="Geeks"))
# Format integers and floats with specified width and precision
print("Geeks :{0:2d}, Portal :{1:8.2f}".format(12, 0.5534))
# Demonstrate order swapping and formatting precision
print("Second argument: {1:3d}, first one: {0:8.2f}".format(47.42, 11))
# Using named arguments for clarity in complex formats
print("Geeks: {a:5d}, Portal: {p:8.2f}".format(a=453, p=59.058))
Output
Number one portal is Geeks, For and Geeks. Geeks :12, Portal : 0.55 Second argument: 11, first one: 47.42 Geeks: 453, Portal: 59.06
In this example:
- {0:2d} and {1:8.2f} demonstrate number formatting where 2d specifies a two-digit integer and 8.2f specifies a floating-point number with two decimal places padded to a total width of eight characters.
- Named arguments a and p are used for additional clarity and are referenced directly in the format string.
Formatting Output using String Method
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. These methods are ideal for organizing textual data neatly in output without using more complex formatting tools.
Example:
cstr = "I love geeksforgeeks"
# Printing the center aligned string with fillchr
print("Center aligned: ")
print(cstr.center(40, '#'))
# Printing the left aligned string with "-" padding
print("left aligned: ")
print(cstr.ljust(40, '-'))
# Printing the right aligned string with "-" padding
print("right aligned: ")
print(cstr.rjust(40, '-'))
Output
Center aligned: ##########I love geeksforgeeks########## left aligned: I love geeksforgeeks-------------------- right aligned: --------------------I love geeksforgeeks
Format Conversion Rule
This table lists the standard format conversion guidelines used by Python’s format() function.
Conversion | Meaning |
---|---|
d | Decimal integer |
b | Binary format |
o | octal format |
u | Obsolete and equivalent to ‘d’ |
x or X | Hexadecimal format |
e or E | Exponential notation |
f or F | Floating-point decimal |
g or G | General format |
c | Single Character |
r | String format(using repr()) |
s | String Format(using str())) |
% | Percentage |