8

Consider this code:

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

What should I write instead of the question mark so that the string will be formatted correctly?

2
  • 1
    'this is {}'.format (self.a) Commented Feb 4, 2014 at 13:29
  • ok, but assume I would like to have the variable name inside my string? Commented Feb 4, 2014 at 13:30

2 Answers 2

16

What you probably are 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)

Note, however, that you are missing at least a method in your class.

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

Sign up to request clarification or add additional context in comments.

2 Comments

It is best to explicitly address the referenced object with {0.a} or similar. {.a} works only once. It fails otherwise like in: "'this is {.a}, i repeat myself {.a}'.format(self)'".
@tssch But if you do this is {.a}, i repeat myself {.a}'.format(self, self), it works. The first self is for the first {.a}, the second one for the second one. As documented.
4

The reference you include inside the brackets refers to either a number indicating the index of the argument passed to format, or a name directing to a named argument in the format call. Like that:

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

2 Comments

This is the correct answer; just fix your code example to actually include a method definition, as OP's example is broken.
hmm, what about using something like format(self.__dict__) or something along those lines so one could easily format with all class members?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.