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

Python | Output Formatting

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

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):
  • 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).



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
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 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
Python DateTime Formatting with Pendulum
Effective date and time management is essential in many applications. Compared to the default datetime module, Pendulum is a Python library that offers a more user-friendly and intuitive interface for manipulating dates. In this article, we will learn about datetime formatting with Pendulum in Python. Python DateTime Formatting with PendulumBelow,
3 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
10 min read
Formatting Cells using openpyxl in Python
When it comes to managing Excel files programmatically, Python offers a powerful tool in the form of the openpyxl library. This library not only allows us to read and write Excel documents but also provides extensive support for cell formatting. From fonts and colors to alignment and borders, openpyxl makes it easy to customize our Excel sheets to
4 min read
Adding Conditional Formatting to Excel Using Python Openpyxl
Adding conditional formatting using openpyxl is an easy and straightforward process. While working with Excel files, conditional formatting is useful for the visualization of trends in the data, highlighting crucial data points, and making data more meaningful and understandable. In this article, we will give a detailed step-by-step explanation for
5 min read
Formatting float column of Dataframe in Pandas
While presenting the data, showing the data in the required format is also a crucial part. Sometimes, the value is so big that we want to show only the desired part of this or we can say in some desired format. Let's see different methods of formatting integer columns and the data frame it in Pandas. Formatting float column of Dataframe in PandasHe
3 min read
Generate two output strings depending upon occurrence of character in input string in Python
Given an input string str[], generate two output strings. One of which consists of that character that occurs only once in the input string and the second consists of multi-time occurring characters. Output strings must be sorted. Examples: Input : str = "geeksforgeeks" Output : String with characters occurring once: "for". String with characters o
4 min read
Python | Testing Output to stdout
Testing is a critical part of development as there is no compiler to analyze the code before Python executes it. Given a program that has a method whose output goes to standard Output (sys.stdout). This almost always means that it emits text to the screen. One likes to write a test for the code to prove that, given the proper input, the proper outp
2 min read
Python | Logging Test Output to a File
Problem - Writing the results of running unit tests to a file instead of printed to standard output. A very common technique for running unit tests is to include a small code fragment (as shown in the code given below) at the bottom of your testing file. Code #1 : import unittest class MyTest(unittest.TestCase): ... if __name__ == '__main__': unitt
2 min read
Python VLC MediaPlayer – Getting Audio Output Devices
In this article we will see how we can get list of output devices of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediPlyer object is the basic object in vlc module for playing the video. Audio o
2 min read
Python VLC Instance - Enumerate the defined audio output devices
In this article we will see how we can get the enumerate audio output devices from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance obje
3 min read
How to write the output to HTML file with Python BeautifulSoup?
In this article, we are going to write the output to an HTML file with Python BeautifulSoup. BeautifulSoup is a python library majorly used for web scraping but in this article, we will discuss how to write the output to an HTML file. Modules needed and installation: pip install bs4 Approach: We will first import all the required libraries.Make a g
2 min read
Writing Scrapy Python Output to JSON file
In this article, we are going to see how to write scrapy output into a JSON file in Python. Using scrapy command-line shell This is the easiest way to save data to JSON is by using the following command: scrapy crawl <spiderName> -O <fileName>.json This will generate a file with a provided file name containing all scraped data. Note tha
2 min read
Click response on video output using Events in OpenCV – Python
OpenCV is a computer vision library that contains various functions to perform operations on Images or videos. OpenCV library can be used to perform multiple operations on videos. In this article, we will create a program with a click response on video output using events in OpenCV Python library. We will be using “cv2.EVENT_LBUTTONDOWN” in case wh
3 min read
How to Disable Output Buffering in Python
Output buffering is a mechanism used by the Python interpreter to collect and store output data before displaying it to the user. While buffering is often helpful for performance reasons there are situations where you might want to disable it to ensure that output is immediately displayed as it is generated especially in the interactive or real-tim
3 min read
Python | Output using print() function
Python print() function prints the message to the screen or any other standard output device. In this article, we will cover about print() function in Python as well as it's various operations. Python print() Function Syntax Syntax : print(value(s), sep= ' ', end = '\n', file=file, flush=flush) Parameters:  value(s): Any value, and as many as you l
8 min read
Retrieving the output of subprocess.call() in Python
The subprocess.call() function in Python is used to run a command described by its arguments. Suppose you need to retrieve the output of the command executed by subprocess.call(). In that case, you'll need to use a different function from the subprocess module, such as subprocess.run(), subprocess.check_output(), or subprocess.Popen(). Introduction
4 min read
Input and Output in Python
Understanding input and output operations is fundamental to Python programming. With the print() function, you can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Python Basic Input and OutputIn this introductory guide, we'll explore the essentials of Python's
8 min read
Biopython - Sequence input/output
Biopython has an inbuilt Bio.SeqIO module which provides functionalities to read and write sequences from or to a file respectively. Bio.SeqIO supports nearly all file handling formats used in Bioinformatics. Biopython strictly follows single approach to represent the parsed data sequence to the user with the SeqRecord object. SeqRecord SeqRecord o
3 min read
How to widen output display to see more columns in Pandas dataframe?
In Python, if there are many more number of columns in the dataframe, then not all the columns will be shown in the output display. So, let's see how to widen output display to see more columns. Method 1: Using pandas.set_option() function. This function is used to set the value of a specified option. Syntax: pandas.set_option(pat, value) Returns:
2 min read
Different Input and Output Techniques in Python3
An article describing basic Input and output techniques that we use while coding in python. Input Techniques 1. Taking input using input() function -> this function by default takes string as input. Example: C/C++ Code #For string str = input() # For integers n = int(input()) # For floating or decimal numbers n = float(input()) 2. Taking Multipl
3 min read
How to get Scrapy Output File in XML File?
Prerequisite: Implementing Web Scraping in Python with Scrapy Scrapy provides a fast and efficient method to scrape a website. Web Scraping is used to extract the data from websites. In Scrapy we create a spider and then use it to crawl a website. In this article, we are going to extract population by country data from worldometers website. Let's i
2 min read
SciPy - Input and Output
In this article, we learn about SciPy input and output. In order to handle inputs and outputs of multiple formats, Scipy.io package provides multiple methods. Some of the formats that can be handled by the Scipy.io package are: MatlabNetcdfIDLArffMatrix MarketWave Among this Matlab is the format which is used very frequently. Now let's see the func
2 min read
Article Tags :
Practice Tags :