首页 > 解决方案 > 为什么我收到此错误?TypeError:“列表”对象不能解释为整数

问题描述

我的代码中出现以下错误我做错了什么:

Traceback (most recent call last):
  File "Solution.py", line 15, in <module>
    print_formatted(n)
  File "Solution.py", line 9, in print_formatted
    print(d.ljust([2,' ']),o.ljust([2,' ']),h.ljust([2,' ']),b.ljust([2,' ']))
TypeError: 'list' object cannot be interpreted as an integer

    TypeError: 'list' object cannot be interpreted as an integer

代码如下所示:

def print_formatted(number):
    for i in range(1,number+1):

        d=str(i)
        o=str(oct(i))[2:]
        h=(str(hex(i))[2:]).capitalize()
        b=str(bin(i))[2:]
        print(d.ljust([2,' ']),o.ljust([2,' ']),h.ljust([2,' ']),b.ljust([2,' ']))


if __name__ == '__main__':
    n = int(input())
    print_formatted(n)

标签: pythonstring

解决方案


ljust接受两个参数,而不是两个元素的列表。用这个:

print(d.ljust(2, ' '), o.ljust(2, ' '), h.ljust(2, ' '), b.ljust(2, ' '))

推荐阅读