The Wayback Machine - https://web.archive.org/web/20250109012603/https://www.geeksforgeeks.org/python-output-formatting/
Open In App

Python – Output Formatting

Last Updated : 16 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Python
# 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
Formatting Output using String Modulo Operator(%)

Output Formatting using Modulo Operator

There are several ways to format output using String Method in Python. 

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:

Python
# 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: 

Formatting Output using The Format Method

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:

Python
# 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:

Python
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

Python | Output Formatting – FAQs

How to do formatting in Python?

In Python, there are multiple ways to format data:

  • String Formatting (.format() method):
  • Formatted String Literals (f-strings) (Python 3.6+):
  • Old-style String Formatting (% operator): This method is less preferred in newer Python code but still works:
name = "Alice"
age = 30
formatted_string = "Name: {}, Age: {}".format(name, age)
print(formatted_string)
# Output: Name: Alice, Age: 30
name = "Alice"
age = 30
formatted_string = f"Name: {name}, Age: {age}"
print(formatted_string)
# Output: Name: Alice, Age: 30
name = "Alice"
age = 30
formatted_string = "Name: %s, Age: %d" % (name, age)
print(formatted_string)
# Output: Name: Alice, Age: 30

How to format .2f in Python?

To format a floating-point number to two decimal places in Python, you can use formatted string literals (f-strings) or the .format() method with specific format specifiers:

  • Using f-string:
  • Using .format() method:
value = 3.14159
formatted_value = f"{value:.2f}"
print(formatted_value)
# Output: 3.14
value = 3.14159
formatted_value = "{:.2f}".format(value)
print(formatted_value)
# Output: 3.14

What is %s formatting in Python?

%s is a placeholder used in old-style string formatting with the % operator. It is used to insert and format strings into a template string. For example:

name = "Alice"
formatted_string = "Hello, %s!" % name
print(formatted_string)
# Output: Hello, Alice!

What is the formatting tool for Python?

Python provides various formatting tools and methods, such as:

  • str.format() method: Introduced in Python 2.7, it offers more flexibility and readability over old-style formatting.
  • Formatted String Literals (f-strings): Introduced in Python 3.6, they provide a concise and readable way to format strings using variables and expressions directly within string literals.
  • % operator: Old-style formatting method, still supported but less recommended for new code due to its limitations compared to str.format() and f-strings.

What is data formatting in Python?

Data formatting in Python refers to the process of converting data from one form or type into another, often for the purpose of display or storage. It involves tasks such as converting numbers to strings with specific formats (like decimal places), formatting dates and times, or organizing data into structured formats (like CSV or JSON).



Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg