内置类型错误:不支持“int”和“str”的操作数类型

2024-09-24 22:26:38 发布

您现在位置:Python中文网/ 问答频道 /正文

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

这里:

^{pr2}$

输出:

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个字符长(即,站1,站2和动物Id)。所以我在打印前加了条件。在

我知道我正在为str和int调用不受支持的操作数(上面显示的位置) 希望你们能帮忙。 谢谢:)

更新: 它打印: 不打印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()

Tags: ofnameidnumbereachstationanimalstimes
1条回答
网友
1楼 · 发布于 2024-09-24 22:26:38

问题在于spacespace2定义:

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

首先,它用一个空格字符乘以长度,这在python中是有效的(字符串只是重复的),但是之后,它尝试计算int 20和字符串之间的减法,后者以TypeError分隔。在

您需要将20-len(visit)括在括号中:

^{pr2}$

演示:

>>> 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))

相关问题 更多 >