Search code examples
pythonstringstring-formatting

Use str.format() to access object attributes


I have a Python object with attributes a, b, c.

I still use old string formatting, so I'd normally print these manually:

 print 'My object has strings a=%s, b=%s, c=%s' % (obj.a, obj.b, obj.c)

Lately, my strings have been getting super long, and I'd much rather be able to simply pass the object into a string format function, something like:

 print 'My object has strings a=%a, b=%b, c=%c'.format(obj)

However, the syntax is incorrect. Is this possible?


Solution

  • You can use the .attribute_name notation inside the format fields themselves:

    print 'My object has strings a={0.a}, b={0.b}, c={0.c}'.format(obj)
    

    Below is a demonstration:

    >>> class Test(object):
    ...     def __init__(self, a, b, c):
    ...         self.a = a
    ...         self.b = b
    ...         self.c = c
    ...
    >>> obj = Test(1, 2, 3)
    >>> 'My object has strings a={0.a}, b={0.b}, c={0.c}'.format(obj)
    'My object has strings a=1, b=2, c=3'
    >>>
    

    Note however that you do need to number the format fields when doing this. Also, as you can see, the str.format function has its format fields denoted by curly braces {...}, not the % sign.

    For more information, here is a reference on the Format String Syntax in Python.