CHAPTER 14 - PYTHON PRINT FORMATTING



AD

This chapter was added to help you make sense of print statements in existing programs you will read.

14.1.0 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 %


14.2.0 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



Engineering-Python

SALARSEN.COM
Table of Contents
Ch1-Install Python
Ch2-Install PyCharm
Ch3-Save Work
Ch4-Add Project
Ch5-Variables
Ch6-Print&Input
Ch7-Lists
Ch8-Loops
Ch9-If&Logical
Ch10-Functions
Ch11-Bubble Sort
Ch12-Plotting
Ch13-Files
Ch14-Print Format
Ch15-Dict&Comp&Zip
Ch16-Arrays
Ch17-Electrical
Ch18-Regression
Ch19-Differential
Ch20-Secant