Strings | String formatting expressions

Basic string formatting expressions

String formatting allows us to perform multiple type-specific substitutions on a
string in a single step.

>>> 'This is %s %s - a %s developer!' % ('Dan', 'Dumitrache', 'web')
'This is Dan Dumitrache - a web developer!'
>>>
>>> 'This is {0} {1} - a {2} developer!'.format('Dan', 'Dumitrache', 'web')
'This is Dan Dumitrache - a web developer!'

A new string is formated!

You can use dictionary based formating expression.

>>> mesaj = 'Hi %(name)s. Are you really %(age)s years old?'
>>> datas = {'name': 'Dan', 'age': 40}
>>> print(mesaj % datas)
Hi Dan. Are you really 40 years old?

Advance string formating expressions

The following example formats integers by default, then in a three-character field with left justification,
and then three-character padding.

>>> num = 8
>>> rez = '...%d...%-3d...%3d' % (num, num, num)
>>> rez
'...8...8  ...  8'

The following example uses %e , %f , and %g formats to display floating-point numbers in different ways, as the following interaction demonstrates – %E is the same as %e but the exponent is uppercase,
and g chooses formats by number content (it’s formally defined to use exponential format e if the exponent is less than −4 or not less than precision, and decimal format f otherwise, with a default total digits precision of 6).

>>> c = 1.23456789
>>> c
1.23456789
>>> 
>>> '%e | %f | %g' % (c, c, c)
'1.234568e+00 | 1.234568 | 1.23457'

Leave a Reply