In Python, output formatting refers to the way data is presented when printed or logged. Proper formatting makes information more understandable and actionable.Pythonprovides several ways to format strings effectively, ranging from old-style formatting to the newerf-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.
Python# string modulo operator(%)print("Geeks :%2d, Portal :%5.2f"%(1,05.333))print("Total students :%3d, Boys :%2d"%(240,120))# print integer valueprint("%7.3o"%(25))# print octal valueprint("%10.3E"%(356.08977))# print exponential value
OutputGeeks : 1, Portal : 5.33Total students : 240, Boys : 120 031 3.561E+02
Output Formatting using Modulo OperatorThere are several ways to format output using String Method inPython.
Formatting Output using The Format Method
Theformat() 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:
Python# Positional formatting with format() method# Using indexed placeholders for string formattingprint("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"))
OutputI love Geeks for "Geeks!"Geeks and PortalPortal 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:
Output Formatting using Format methodAdvanced 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:
Python# Advanced formatting with positional and named arguments# Mixing positional and named argumentstemplate="Number one portal is{0},{1} and{other}."print(template.format("Geeks","For",other="Geeks"))# Format integers and floats with specified width and precisionprint("Geeks :{0:2d}, Portal :{1:8.2f}".format(12,0.5534))# Demonstrate order swapping and formatting precisionprint("Second argument:{1:3d}, first one:{0:8.2f}".format(47.42,11))# Using named arguments for clarity in complex formatsprint("Geeks:{a:5d}, Portal:{p:8.2f}".format(a=453,p=59.058))
OutputNumber one portal is Geeks, For and Geeks.Geeks :12, Portal : 0.55Second argument: 11, first one: 47.42Geeks: 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 asstr.center(),str.ljust() andstr.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:
Pythoncstr="I love geeksforgeeks"# Printing the center aligned string with fillchrprint("Center aligned: ")print(cstr.center(40,'#'))# Printing the left aligned string with "-" paddingprint("left aligned: ")print(cstr.ljust(40,'-'))# Printing the right aligned string with "-" paddingprint("right aligned: ")print(cstr.rjust(40,'-'))
OutputCenter 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 |
Output Formatting in Python