Open In App

Python | Output Formatting

Last Updated : 20 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Python, there are several ways to present the output of a program. Data can be printed in a human-readable form, or written to a file for future use, or even in some other specified form. Users often want more control over the formatting of output than simply printing space-separated values.

Output Formatting in Python

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

  • Using String Modulo Operator(%)
  • Using Format Method
  • Using The String Method
  • Python’s Format Conversion Rule

Formatting Output using String Modulo Operator(%)

The Modulo % operator can also be used for string formatting. It interprets the left argument much like a printf()-style format as in C language strings to be applied to the right argument. In Python, there is no printf() function but the functionality of the ancient printf is contained in Python. To this purpose, the modulo operator % is overloaded by the string class to perform string formatting. Therefore, it is often called a string modulo (or sometimes even called modulus) operator. The string modulo operator ( % ) is still available in Python(3.x) and is widely used. But nowadays the old style of formatting is removed from the language. 

Python
# Python program showing how to use 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 two of those in our example: “%2d” and “%5.2f”. The general syntax for a format placeholder is: 

 %[flags][width][.precision]type 

Let’s take a look at the placeholders in our example.  

  • The first placeholder ‘%2d’ is used for the first component of our tuple, i.e. the integer 1. It will be printed with 2 characters, and as 1 consists of only one digit, the output is padded with 1 leading blank.
  • The second placeholder ‘%5.2f’ is for a float number. Like other placeholders, it’s introduced with the % character. It specifies the total number of digits the string should contain, including the decimal point and all the digits, both before and after the decimal point.
  • Our float number 05.333 is formatted with 5 characters and a precision of 2, denoted by the number following the ‘.’ in the placeholder. The last character ‘f’ indicates that the placeholder represents a float value.

Formatting Output using The Format Method

The format() method was added in Python(2.6). The format method of strings requires more manual effort. Users use {} to mark where a variable will be substituted and can provide detailed formatting directives, but the user also needs to provide the information to be formatted. This method lets us concatenate elements within an output through positional formatting. For Example – 

Example 1: The code explain various Python string formatting techniques.The values are either explicitly supplied or referred to by the order in which they appear in the format() procedure.f-Strings enable the use of curly braces and the f prefix to embed expressions inside string literals. The f-Strings’ expressions are assessed and their appropriate values are substituted for them.

Python
print('I love {} for "{}!"'.format('Geeks', 'Geeks'))

# using format() method and referring a position of the object
print('{0} and {1}'.format('Geeks', 'Portal'))

print('{1} and {0}'.format('Geeks', 'Portal'))

print(f"I love {'Geeks'} for \"{'Geeks'}!\"")

# using format() method and referring a position of the object
print(f"{'Geeks'} and {'Portal'}")

Output

I love Geeks for "Geeks!"
Geeks and Portal
Portal and Geeks
I love Geeks for "Geeks!"
Geeks and Portal

The brackets and characters within them (called format fields) are replaced with the objects passed into the format() method. A number in the brackets can be used to refer to the position of the object passed into the format() method. 
  
Example 2:With the help of positional parameters and a named argument (‘other’) in the first line, the values ‘Geeks’, ‘For’, and ‘Geeks’ are added to the string template.’Geeks:12, Portal: 0.55′ is printed, with the first value appearing as a 2-digit integer and the second number having 2 decimal places and an 8-bit width. The format() method’s named arguments, denoted by specific labels (‘a’ and ‘p’) for the numbers ‘453’ and ‘59.058’,

Python
# combining positional and keyword arguments
print('Number one portal is {0}, {1}, and {other}.'
     .format('Geeks', 'For', other ='Geeks'))

# using format() method with number 
print("Geeks :{0:2d}, Portal :{1:8.2f}".
      format(12, 00.546))

# Changing positional argument
print("Second argument: {1:3d}, first one: {0:7.2f}".
      format(47.42, 11))

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

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

Example 3:The code shows how to use dictionaries with Python’s format() method. The dictionary’s ‘tab’ in the first example has keys and associated values. The format() method uses indexing to put the values into the string template. In the second example, named keys in a dictionary are used as “data.

Python
tab = {'geeks': 4127, 'for': 4098, 'geek': 8637678}

# using format() in dictionary
print('Geeks: {0[geeks]:d}; For: {0[for]:d}; '
    'Geeks: {0[geek]:d}'.format(tab))

data = dict(fun ="GeeksForGeeks", adj ="Portal")

print("I love {fun} computer {adj}".format(**data))

Output

Geeks: 4127; For: 4098; Geeks: 8637678
I love GeeksForGeeks computer Portal

Formatting Output using The String Method

This output is formatted by using string method i.e. slicing and concatenation operations. The string type has some methods that help in formatting output in a fancier way. Some methods which help in formatting an output are str.ljust(), str.rjust(), and str.centre()

Python
cstr = "I love geeksforgeeks"

# Printing the center aligned string with fillchr
print("Center aligned string with fillchr: ")
print(cstr.center(40, '#'))

# Printing the left aligned string with "-" padding
print("The left aligned string is : ")
print(cstr.ljust(40, '-'))

# Printing the right aligned string with "-" padding
print("The right aligned string is : ")
print(cstr.rjust(40, '-'))

Output

Center aligned string with fillchr: 
##########I love geeksforgeeks##########
The left aligned string is :
I love geeksforgeeks--------------------
The right aligned string is :
--------------------I love geeksforgeeks

Python’s 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):
    name = "Alice"
    age = 30
    formatted_string = "Name: {}, Age: {}".format(name, age)
    print(formatted_string)
    # Output: Name: Alice, Age: 30
  • Formatted String Literals (f-strings) (Python 3.6+):
    name = "Alice"
    age = 30
    formatted_string = f"Name: {name}, Age: {age}"
    print(formatted_string)
    # Output: Name: Alice, Age: 30
  • Old-style String Formatting (% operator): This method is less preferred in newer Python code but still works:
    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:
    value = 3.14159
    formatted_value = f"{value:.2f}"
    print(formatted_value)
    # Output: 3.14
  • Using .format() method:
    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).



Previous Article
Next Article

Similar Reads

JSON Formatting in Python
JSON (JavaScript Object Notation) is a popular data format that is used for exchanging data between applications. It is a lightweight format that is easy for humans to read and write, and easy for machines to parse and generate. Python Format JSON Javascript Object Notation abbreviated as JSON is a lightweight data interchange format. It encodes Py
3 min read
Python code formatting using Black
Writing well-formatted code is very important, small programs are easy to understand but as programs get complex they get harder and harder to understand. At some point, you can’t even understand the code written by you. To avoid this, it is needed to write code in a readable format. Here Black comes into play, Black ensures code quality. What is B
3 min read
Formatting Axes in Python-Matplotlib
Matplotlib is a python library for creating static, animated and interactive data visualizations. Note: For more information, refer to Introduction to Matplotlib What is Axes? This is what you think of as 'plot'. It is the region of the image that contains the data space. The Axes contains two or three-axis(in case of 3D) objects which take care of
4 min read
Formatting containers using format() in Python
Let us see how to format containers that were accessed through __getitem__ or getattr() using the format() method in Python. Accessing containers that support __getitem__a) For Dictionaries C/C++ Code # creating a dictionary founder = {'Apple': 'Steve Jobs', 'Microsoft': 'Bill Gates'} # formatting print('{f[Microsoft]} {f[Apple]}'.format(f = founde
1 min read
Python - Split strings ignoring the space formatting characters
Given a String, Split into words ignoring space formatting characters like \n, \t, etc. Input : test_str = 'geeksforgeeks\n\r\\nt\t\n\t\tbest\r\tfor\f\vgeeks' Output : ['geeksforgeeks', 'best', 'for', 'geeks'] Explanation : All space characters are used as parameter to join. Input : test_str = 'geeksforgeeks\n\r\\nt\t\n\t\tbest' Output : ['geeksfor
3 min read
Paragraph Formatting In Python .docx Module
Prerequisite: Working with .docx module Word documents contain formatted text wrapped within three object levels. The Lowest level- run objects, middle level- paragraph objects, and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the pytho
9 min read
Hover Text and Formatting in Python-Plotly
Prerequisites: Python Plotly In this article, we will explore how to Hover Text and Formatting in Python. It is a useful approach to Hover Text and Formatting as it allows to reveal a large amount of data about complex information. One of the most deceptively-powerful features of data visualization is the ability for a viewer to quickly analyze a s
2 min read
Python String Formatting - How to format String?
String formatting allows you to create dynamic strings by combining variables and values. In this article, we will discuss about 5 ways to format a string. You will learn different methods of string formatting with examples for better understanding. Let's look at them now! How to Format Strings in PythonThere are five different ways to perform stri
8 min read
Python Modulo String Formatting
In Python, a string of required formatting can be achieved by different methods. Some of them are; 1) Using % 2) Using {} 3) Using Template Strings In this article the formatting using % is discussed. The formatting using % is similar to that of 'printf' in C programming language. %d - integer %f - float %s - string %x - hexadecimal %o - octal The
2 min read
Formatting Dates in Python
In different regions of the world, different types of date formats are used and for that reason usually, programming languages provide a number of date formats for the developed to deal with. In Python, it is dealt with by using a liberty called DateTime. It consists of classes and methods that can be used to work with data and time values. Require
5 min read
Article Tags :
Practice Tags :