I want to print the values from the dunder methods of a class foo
. However, I got the error:
IndexError: Replacement index 1 out of range for positional args tuple
The code snippet is as follows:
class foo(object):
def __str__(self):
return 'Testing'
def __repr__(self):
return 'Programming'
print('{}{}'.format(foo()))
CodePudding user response:
Your template string has two placeholders while you pass only one value in the .format()
call. .format()
will only execute __str__
, not __repr__
. You should either use
print('{}'.format(foo()))
or
my_foo = foo()
print('{}{}'.format(my_foo, repr(my_foo)))
As a side note, class names should be in title case (Foo
) per PEP-8.
CodePudding user response:
I did the following and it gave me the desired output.
class foo (object):
def __str__(self):
return 'Testing'
def __repr__(self):
return 'Programming'
print('{0!s}{0!r}'.format(foo(),repr(foo)))
Output:
TestingProgramming