Python | Output Formatting
Last Updated :
20 Jun, 2024
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
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:Â
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:
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).
Please Login to comment...