Friday, December 27, 2024
Google search engine
HomeLanguagesPython | Output Formatting

Python | Output Formatting

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. 

Python3




# 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.

Python3




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’,

Python3




# 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.

Python3




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()

Python3




cstr = "I love neveropen"
 
# 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 neveropen##########
The left aligned string is : 
I love neveropen--------------------
The right aligned string is : 
--------------------I love neveropen

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

RELATED ARTICLES

Most Popular

Recent Comments