builtins.TypeError:不支持的操作数类型(-):'int'和'str

0 投票
1 回答
2800 浏览
提问于 2025-04-18 01:25
def printsection1(animals, station1, station2):
    animals=['a01', 'a02', 'a03', 'a04', 'a05']
    station1={'a04': 5, 'a05': 1, 'a03': 62, 'a01': 21}
    station2={'a04': 5, 'a02': 3, 'a03': 4, 'a01': 1}

    print('Number of times each animal visited each station :')
    print('Animal Id'+' '*11+'Station 1'+' '*11+'Station 2'+'           ')

    for name in animals:
        if name in station1:
            visit=str(station1.get(name))
        else:
            visit=0
        if name in station2:
            visit2=str(station2.get(name))
        else:
            visit2=0

在这里:

        space=(20-len(visit2))*' '

        print(name+' '*17+str(visit)+space+str(visit2))
    print('='*60)

输出:

Number of times each animal visited each station :
Animal Id           Station 1           Station 2           
a01                 21                  1                  
a02                 0                   3                  
a03                 62                  4                  
a04                 5                   5    
a05                 1                   0 

============================================================

大家好

我在做一个程序,这里是其中的一部分。我想打印出上面显示的内容。

但是我总是遇到一个错误 builtins.TypeError: object of type 'int' has no len()。它打印了所有内容,除了 a05

我想让每一列的长度都正好是20个字符(比如 station1、station2 和动物 ID)。所以我在打印之前加了一个条件。

我明白我在调用一个不支持的操作,涉及到字符串和整数(上面的位置显示了)。希望你们能帮帮我。

谢谢 :)

更新: 它打印了: 没有打印 a05

Number of times each animal visited each station :
Animal Id           Station 1           Station 2           
a01                 21                  1
a02                 0                   3
a03                 62                  4
a04                 5                   5
builtins.TypeError: object of type 'int' has no len()

1 个回答

1

这个问题出在 spacespace2 的定义上:

space=20-len(visit)*' '
space2=20-len(visit2)*' '

首先,它把长度乘以一个空格字符,这在 Python 中是可以的(字符串会简单地重复),但是接下来,它试图计算一个整数 20 和这个字符串之间的减法,这就会出现 TypeError 错误。

你需要把 20-len(visit) 用括号括起来:

space=(20 - len(visit)) * ' '
space2=(20 - len(visit2)) * ' ' 

示例:

>>> visit = 'test'
>>> space=20-len(visit)*' '
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'int' and 'str'

>>> space=(20-len(visit))*' '
>>> space
'                '

此外,之后 space 变量在下面的代码中被使用:

print(name+' '*17+str(visit)+space+str(visit2))

此时 space 是一个 int 类型 - 你需要把它转换成字符串:

print(name+' '*17+str(visit)+str(space)+str(visit2))

撰写回答