Python – Output Formatting
Last Updated :
16 Dec, 2024
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.
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
OutputGeeks : 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.
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"))
OutputI 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:
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))
OutputNumber 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.
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, '-'))
OutputCenter aligned:
##########I love geeksforgeeks##########
left aligned:
I love geeksforgeeks--------------------
right aligned:
--------------------I love geeksforgeeks
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
|
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
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
%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!
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.
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).
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial - Python is one of the most popular programming languages today, known for its simplicity and extensive features. Its clean and straightforward syntax makes it beginner-friendly, while its powerful libraries and frameworks makes it perfect for developers. A high-level, interpreted la
10 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. Print Output in PythonAt its core, printing out
7 min read
Python basic I/O Techniques
Taking input in Python
Developers often have a need to interact with users, either to get data or to provide some sort of result. Most programs today use a dialog box as a way of asking the user to provide some type of input. While Python provides us with two inbuilt functions to read the input from the keyboard. input ()
3 min read
Python input() Function
Python input() function is used to take user input. By default, it returns the user input in form of a string. input() Function Syntax: input(prompt)prompt [optional]: any string value to display as input message Ex: input("What is your name? ") Returns: Return a string value as input by the user.
4 min read
Taking input from console in Python
What is Console in Python? Console (also called Shell) is basically a command line interpreter that takes input from the user i.e one command at a time and interprets it. If it is error free then it runs the command and gives required output otherwise shows the error message. A Python Console looks
2 min read
Python - Print 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. [GFGTABS] Python # print() function example print("GeeksforGeeks") a = [1, 2, 'gfg'] pri
4 min read
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 Ou
6 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 de
3 min read
Python 3 - input() function
In Python, we use the input() function to take input from the user. Whatever you enter as input, the input function converts it into a string. If you enter an integer value still input() function converts it into a string. Python input() Function SyntaxSyntax: input(prompt) Parameter: Prompt: (optio
3 min read
Some additional Python Input techniques
How to set an input time limit in Python?
In this article, we will explain how to set an input time limit in Python. It is one of the easiest programming languages which is not only dynamically typed but also garbage collected. Here we will look at different methods to set an input time limit. Below are the methods we will use in this artic
6 min read
Take input from stdin in Python
In this article, we will read How to take input from stdin in Python. There are a number of ways in which we can take input from stdin in Python. sys.stdininput()fileinput.input()Read Input From stdin in Python using sys.stdin First we need to import sys module. sys.stdin can be used to get input fr
2 min read
How to take integer input in Python?
In this post, We will see how to take integer input in Python. As we know that Python's built-in input() function always returns a str(string) class object. So for taking integer input we have to type cast those inputs into integers by using Python built-in int() function. Let us see the examples: E
3 min read
Difference between input() and raw_input() functions in Python
Developers often have a need to interact with users, either to get data or to provide some sort of result. Most programs today use a dialog box as a way of asking the user to provide some type of input. While Python provides us with two inbuilt functions to read the input from the keyboard. input (
4 min read
Taking multiple inputs from user in Python
While taking a single input from a user is straightforward using the input() function, many real world scenarios require the user to provide multiple pieces of data at once. This article will explore various ways to take multiple inputs from the user in Python. Using input() and split()One of the si
5 min read
How to Take Only a Single Character as an Input in Python
Through this article, you will learn how to accept only one character as input from the user in Python. Prompting the user again and again for a single character To accept only a single character from the user input: Run a while loop to iterate until and unless the user inputs a single character.If
3 min read
Difference between input() and sys.stdin.readline()
Python is a widely used general-purpose language that can be used for many purposes. Taking input in any language is as important as breathing for humans. Python provides various methods for taking input. However, we all may get confused about how each method is different from one another. In this a
2 min read
How to input multiple values from user in one line in Python?
For instance, in C we can do something like this: C/C++ Code // Reads two values in one line scanf("%d %d", &x, &y) One solution is to use raw_input() two times. C/C++ Code x, y = input(), input() Another solution is to use split() C/C++ Code x, y = input().split()
2 min read
Python Inputs for Competitive Programming
Python Input Methods for Competitive Programming
Python is an amazingly user-friendly language with the only flaw of being slow. In comparison to C, C++, and Java, it is quite slower. In online coding platforms, if the C/C++ limit provided is x. Usually, in Java time provided is 2x, and in Python, it's 5x. To improve the speed of code execution fo
6 min read
Fast I/O for Competitive Programming in Python
In Competitive Programming, it is important to read input as fast as possible to save valuable time. Input/Output in Python can be sometimes time taking in cases when the input is huge or to output any numbers of lines or a huge number of arrays(lists) line after line. Fast Input Normally, the input
3 min read