python - 如何对齐 __str__ 输出中的列表?

标签 python python-3.x string list

当我向下面的代码添加对齐时

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)

特别是它的列表参数,例如

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)

我收到错误:

TypeError: unsupported format string passed to list.__format__

正确的做法是什么?

最佳答案

使用 conversion flag 强制列表的字符串表示形式:

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

发生这种情况的原因是 list.__format__ 不支持格式字符串迷你语言中的对齐。 format string syntax 的文档详细描述一下此转换功能的工作原理。

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.

同样的事情可以用于 f 字符串,语法如下:

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

关于python - 如何对齐 __str__ 输出中的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69533581/

相关文章:

c - 通过使用 strsep 拆分来解析 CSV 文件

python - 查看系统音量是否静音?

python - manage.py 运行服务器

python - pytesseract 输出未定义

Python MySQL INSERT 查询未执行

python - `tf.set_random_seed()` 相当于操作种子?

python 3 : Split string under certain condition

字符串数组(字符)的 C++ 元素依赖于源字符串

python - pysftp。根据修改日期获取文件

python - 仅打印最终结果而不是所有中间结果