string formatting and usage of dict in it



 

String formatting using dictionary


instead of %s use %(key of dict)s

>>> data = {'arg1': 'lady gaga', 'arg2': 'shreya ghoshal'}

>>> '%(arg1)s is awesome, %(arg2)s love you sooo much' % data

'lady gaga is awesome, shreya ghoshal love you sooo much'

when same value needed to be replace in may places use string multiplication

>>> s='funny'
>>> string='%s ~~~~ %s +++++ %s ----' % (3*(s,))
>>> string
'funny ~~~~ funny +++++ funny ----'

Comman string  formatting 

String :

>>> x = "python"
>>> print "hai %s" %(x,)
hai python

Int :
>>> y = 19
>>> print "value =  %d" %(y,)
value =  19

Float:
>>> z = 12.98765
>>> print "value =  %f" %(z,)
value =  12.987650
>>> print "value =  %.2f" %(z,)
value =  12.99
>>> print "value =  %.3f" %(z,)
value =  12.988