Flame of udun
Flame of udun

Reputation: 2237

How is this string being formatted in python

I am going through a tutorial for a python library. Found this example code :

>>> device = monitor.poll(timeout=3)
>>> if device:
...     print('{0.action}: {0}'.format(device))
...

I know the meaning of {0} and in this .format() template. What does {0.action} mean and how does it get processed?

Upvotes: 1

Views: 38

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 121987

An instructive example:

>>> class Device:
    def __init__(self):
        self.action = "bar"
    def __str__(self):
        return "foo"


>>> device = Device()
>>> print('{0.action}: {0}'.format(device))
bar: foo

The "dot notation" instance.attribute can be used to access attributes in str.format just as it can elsewhere.

Upvotes: 4

Related Questions