Python string formatting

Consider this code:

class Foo:
  def geta(self):
    self.a = 'lie'
    return 'this is {self.a}'.format(?)

What should be written instead of a question mark so that the string is formatted correctly?

+4
source share
2 answers

What you are probably looking for is

'this is {0.a}'.format(self)
'this is {.a}'.format(self)
'this is {o.a}'.format(o=self)
'this is {self.a}'.format(self=self)

Please note, however, that you do not even have a mechod in your class.

Directly under the scope of the class there is no such thing as self.

+8
source

The link that you include in brackets is a number that indicates the index of the argument passed to the format, or a name that directs the named argument in the format call. For example:

class Foo:
  def geta(self):
    self.a = 'lie'
    return 'this is {self.a}'.format(self=self)
+3
source

Source: https://habr.com/ru/post/1525233/


All Articles