当我向下面的代码添加对齐时
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/