How to remove [] on __repr__ return

681 views Asked by At

When using repr to test the class that I have created, I always get brackets around my printed value.

ex)

def __repr__(self):
    return ("H")

runs in shell as [H, H, H, H] for 4 lines. I want to remove the brackets and the commas but am unsure how to do this using repr. Do i need to create another method that repr returns instead?

Thank you for you help.

2

There are 2 answers

0
Jason Hu On

you must hide some thing. i think you have a list to contain all your instances, that's why you see a pair of [, ].

i don't have any such issue.

>>> class A:
    def __repr__(self):
        return "a"


>>> 
>>> A()
a

i think this seems to be your situation:

>>> [A(),A()]
[a, a]
0
Noctis Skytower On

Your example is not very clear, but I think the following code might demonstrate what you want:

>>> class Example:

    def __repr__(self):
        return 'H'


>>> array = [Example() for _ in range(4)]
>>> array
[H, H, H, H]
>>> class ArrayWithoutBrackets(list):

    def __repr__(self):
        return super().__repr__()[1:-1]


>>> array = ArrayWithoutBrackets()
>>> for _ in range(4):
    array.append(Example())


>>> array
H, H, H, H