Home > Blockchain >  How to align a list in an __str__ output?
How to align a list in an __str__ output?

Time:10-12

When I add alignment to the code below

class MyClass():

    def __init__(self, a = None, b = [], c = None):
        self.a = a
        self.b = b
        self.c = c

    def __str__(self):
        return "a: {}, b: {}, c:{}".format(
            self.a, self.b, self.c)

if __name__ == "__main__":
    obj = MyClass(1, [1,2], 2)
    print(obj)

in particular, to its list argument, like

class MyClass():

    def __init__(self, a = None, b = [], c = None):
        self.a = a
        self.b = b
        self.c = c

    def __str__(self):
        return "a: {:<3}, b: {:<3}, c:{:<3}".format(
            self.a, self.b, self.c)

if __name__ == "__main__":
    obj = MyClass(1, [1,2], 2)
    print(obj)

I get an error:

TypeError: unsupported format string passed to list.__format__

What is the right way to do so?

CodePudding user response:

Force the string representation of the list with a conversion flag:

def __str__(self):
    return "a: {:<3}, b: {!s:<3}, c:{:<3}".format(
        self.a, self.b, self.c)

The reason this happens is that list.__format__ doesn't support alignment in the format string mini-language. The docs for format string syntax describe a bit more about how this conversion feature works.

The conversion field causes a type coercion before formatting. Normally, the job of formatting a value is done by the __format__() method of the value itself. However, in some cases it is desirable to force a type to be formatted as a string, overriding its own definition of formatting. By converting the value to a string before calling __format__(), the normal formatting logic is bypassed.

The same thing can be used with f-strings, with a syntax like this:

>>> f"{[1, 2]!s:>10}"
'    [1, 2]'

CodePudding user response:

It looks like alignment is not supported for list objects. Try changing your code to:

def __str__(self):
    return "a: {:<3}, b: {:<3}, c:{:<3}".format(
        self.a, str(self.b), self.c)
  • Related