gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 09:30:30 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com