Skip to content

Instantly share code, notes, and snippets.

@arwer13
Created May 16, 2016 20:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arwer13/ad739247fab955487012f95b5a6ab7ff to your computer and use it in GitHub Desktop.
Save arwer13/ad739247fab955487012f95b5a6ab7ff to your computer and use it in GitHub Desktop.

.format was introduced in Python2.6 It is more powerful than %.

The most common use:

>>> '{}, {}, {}'.format('a', 'b', 'c')
'a, b, c'

>>> '{2}, {1}, {0}, {1}'.format('a', 'b', 'c')
'c, b, a, b'

One may pass variables as named arguments:

>>> '({x}, {y}): {object}'.format(x=1, y=2, object='apple')
'(1,2): apple'

It's very convenient to use this with dictionary unpacking

>>> info = {'x': 1, 'y': 2, 'object': 'apple'}
>>> '({x}, {y}): {object}'.format(**info)
'(1,2): apple'

Or tuple arguments unpacking

info = ('a' 'b', 'c')
>>> '{2}, {1}, {0}, {1}'.format(*info)
'c, b, a, b'

There are also a lot of special formatters related to floats, hex, dates etc. For example

>>> '{0:.4f}'.format(342.34254234)
'342.3425'

and

>>> '{:06}'.format(123)
'000123'

Links:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment