Skip to content

Instantly share code, notes, and snippets.

@draganHR
Created November 26, 2015 09:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save draganHR/aa1a70a190386ef5ce71 to your computer and use it in GitHub Desktop.
Save draganHR/aa1a70a190386ef5ce71 to your computer and use it in GitHub Desktop.
Cheat sheet for "new style" string formatting in Python 2.6.

Cheat sheet for "new style" string formatting in Python 2.6. It is modified version of examples from http://pyformat.info/ Difference is that simplest sytaxt ( '{}'.format('foo') ) does not work in Python 2.6 and you need to specify value index for each value ( '{0}'.format('foo') ).

Format:

'{1} {0}'.format('one', 'two')

Align right:

'{0:>10}'.format('test')

Align left:

'{0:10}{1}'.format('test', '...')

Align by argument:

'{0:<{1}s}'.format('test', 8)

Truncate:

'{0:.5}'.format('xylophone')

Trucate by argument:

'{0:.{1}}'.format('xylophone', 7)

Combining truncating and padding

'{0:10.5}'.format('xylophone')

Number:

'{0:d}'.format(42)

Floats:

'{0:f}'.format(3.141592653589793)

Padding numbers

'{0:4d}'.format(42)
'{0:06.2f}'.format(3.141592653589793)
'{0:04d}'.format(42)

Signed numbers

'{0:+d}'.format(42)
'{0: d}'.format(-23)
'{0:=5d}'.format(-23)

Named placeholders

data = {
    'first': 'Hodor',
    'last': 'Hodor!',
}
'{first} {last}'.format(**data)
'{first} {last}'.format(first="Hodor", last="Hodor!")

Getitem and Getattr

person = {
    'first': 'Jean-Luc',
    'last': 'Picard',
}
'{p[first]} {p[last]}'.format(p=person)

data = [4, 8, 15, 16, 23, 42]
'{d[4]} {d[5]}'.format(d=data)

class Plant(object):
    type = "tree"
'{p.type}'.format(p=Plant())

class Plant(object):
    type = "tree"
    kinds = [{
        'name': "oak",
    }, {
        'name': "maple"
    }]
'{p.type}: {p.kinds[0][name]}'.format(p=Plant())

Datetime

from datetime import datetime
'{0:%Y-%m-%d %H:%M}'.format(datetime(2001, 2, 3, 4, 5))


class HAL9000(object):
    def __format__(self, format):
        if format == "open-the-pod-bay-doors":
            return "I'm afraid I can't do that."
        return "HAL 9000"
'{0:open-the-pod-bay-doors}'.format(HAL9000())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment