Day 57: Python string format library


python format

Yes, we’re talking about that one.

In the world of strings

Strings are everywhere in python.

And we’re not talking about that other piece of clothing.

The old way of doing things

Remember the days of the %d for ‘decimals’ and %s for ‘strings’ ?

Well, if you didn’t know, those days are gone.

The new way

The new way is way more intuitive and we use a pair of curly braces to represent an ‘object’

1. It starts with a single quote




We basically say, there is a string, that string needs to be formatted, and here’s the data coming.

2. Double object




3. Let’s space things up

'{}{}'.format('double ','object')


'double object'

4. There is a better way to space

'{} {}'.format('double','object')


'double object'

5. Don’t like spaces ?




6. Did you say positional ?




7. Can we get a var in the mix ?

>>> var1 = "over"
>>> var2 = "under"
>>> '{}_{}'.format(var1,var2)
>>> '{1}_{0}'.format(var1,var2)

8. Did you say rainbow ?

>>> '{} {} {}'.format(var1,var2,'the rainbow')
'over under the rainbow'

9. No, I meant rain.

>>> '{} {} {:.8}'.format(var1,var2,'the rainbow')
'over under the rain'

10. Let’s stay under.

>>> '{:.0} {} {:.8}'.format(var1,var2,'the rainbow')
' under the rain'

11. Are you lagging? or multiplying ?

>>> '{0} {0} {1} {1} {2} {2}'.format(var1,var2,'the rainbow')
'over over under under the rainbow the rainbow'

\ Codarren /


python string formatting

Written on February 26, 2021