CHAPTER 11 - PYTHON PRINT FORMATTING



AD

11.1 Python printing with the % operator

The % operator has been around for a long time. Take a look at the following examples.

#Python Output Formatting
#PyFormat Old and New, % and .format


# Python program showing how to use
# string modulo operator(%) to print


# print integer and float value
print("Geeks : % 2d, Portal : % 5.2f" % (1, 05.333))
#Output Geeks : 1, Portal : 5.33


# print integer value
print("Total students : % 3d, Boys : % 2d" % (240, 120))
#Output Total students : 240, Boys : 120


# print exponential value
print("% 10.3E" % (356.08977))
#Output 3.561E+02


#Formatting a floating point number
print('%d %s cost $%.2f' % (6, 'apples', 1.765))
#Output 6 apples cost $1.76


#Escaping a % sign
print("Percent %s %%" % (35))
#Output Percent 35 %


11.2 Python printing with .format

Printing with .format is the newer way to format print statements. Take a look at the following examples.


# Python program showing
# a use of format() method


# combining positional and keyword arguments
print('Portal is {0}, {1}, and {other}.'.format('Geeks', 'For', other='Geeks'))
#Output Portal is Geeks, For, and Geeks.


# switching positional arguments
print('Portal is {1}, {0}, and {other}.' .format('Geeks', 'For', other='Geeks'))
#Output Portal is For, Geeks, and Geeks.


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


#Printing % sign
print ("Percent {}%" .format(35))
#Output Percent 35%


print("Formatted Number with percent: "+"{:.2%}".format(2455))
#Output Formatted Number with percent: 245500.00%


print('{0} {1} cost ${2:.2f}' .format(6, 'apples', 1.765))
#Output 6 apples cost $1.76


theSurfDragon.com


Python Navigation

Table of Contents
Ch1-Starting Out
Ch2-Loops
Ch3-If Statements
Ch4-Functions
Ch5-Variable Scope
Ch6-Bubble Sort
Ch7-Intro to OOP
Ch8-Inheritance
Ch9-Plotting
Ch10-Files
Ch11-Print Format
Ch12-Dict-Zip-Comp
Ch13-Slice Arrays