Print Formatting Practice (Numbers and Strings)


In [8]:
print("My number %s" %("hello"))


My number hello

In [11]:
s=13.4576

print('Floating point: %1.3f' %(s))
print('FLoating point value appending zeros: %1.8f' %(s))
print('Floating point with filled in spaces: %25.4f'  %(s))


Floating point: 13.458
FLoating point value appending zeros: 13.45760000
Floating point with filled in spaces:                   13.4576

%x.yf format: x->Minimum number of characters for the string, y-> number of digits after the decimal point.

Multiple formating

You can print multiple objects or values at same time.


In [7]:
print('First: %s, Second: %1.1f and Third: %s' %(1,2.0,"three"))


First: 1, Second: 2.0 and Third: three

The values will follow order of appearance (same as in C's printf())

Conversion methods

%s and %r are 2 conversion methods, they convert any python object to a string.

%s uses str() and %r uses repr().


In [20]:
print('This is object to string using %s & %s' %(1234,"String here!"))


This is object to string using 1234 & String here!

In [22]:
print('This is object to string using %r & %r' %(4321,"String here!"))


This is object to string using 4321 & 'String here!'

String .format() method


In [13]:
a=2
b=3
c=a+b
print('The sum is: {res}'.format(res=c))


The sum is: 5

In [14]:
print('First: {x}, Second: {y} and Third: {z}'.format(x=1, y=2.0, z="three"))


First: 1, Second: 2.0 and Third: three

You can print the same value more than once.


In [15]:
print('First: {x}, Second: {y} and again First: {x}'.format(x=1, y=2))


First: 1, Second: 2 and again First: 1

No need to worry about the order here.


In [ ]: