TypeError:不能将“int”对象隐式转换为str

我正在尝试编写一个文本游戏,并且在我定义的函数中遇到了一个错误,让您在创buildangular色之后基本上可以使用技能点。 起初,错误指出,我正试图从这部分代码中的整数减去一个string: balance - strength 。 显然这是错误的,所以我用strength = int(strength)修正它…但是现在我得到了这个我以前从来没有见过的错误(新程序员),我很难确定它到底想告诉我什么,我修复它。

这里是我的代码为不工作的部分function:

 def attributeSelection(): balance = 25 print("Your SP balance is currently 25.") strength = input("How much SP do you want to put into strength?") strength = int(strength) balanceAfterStrength = balance - strength if balanceAfterStrength == 0: print("Your SP balance is now 0.") attributeConfirmation() elif strength < 0: print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!") attributeSelection() elif strength > balance: print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!") attributeSelection() elif balanceAfterStrength > 0 and balanceAfterStrength < 26: print("Ok. You're balance is now at " + balanceAfterStrength + " skill points.") else: print("That is an invalid input. Restarting attribute selection.") attributeSelection() 

当我到达shell的这部分代码的时候,这里是我得到的错误:

  Your SP balance is currently 25. How much SP do you want to put into strength?5 Traceback (most recent call last): File "C:\Python32\APOCALYPSE GAME LIBRARY\apocalypseGame.py", line 205, in <module> gender() File "C:\Python32\APOCALYPSE GAME LIBRARY\apocalypseGame.py", line 22, in gender customizationMan() File "C:\Python32\APOCALYPSE GAME LIBRARY\apocalypseGame.py", line 54, in customizationMan characterConfirmation() File "C:\Python32\APOCALYPSE GAME LIBRARY\apocalypseGame.py", line 93, in characterConfirmation characterConfirmation() File "C:\Python32\APOCALYPSE GAME LIBRARY\apocalypseGame.py", line 85, in characterConfirmation attributeSelection() File "C:\Python32\APOCALYPSE GAME LIBRARY\apocalypseGame.py", line 143, in attributeSelection print("Ok. You're balance is now at " + balanceAfterStrength + " skill points.") TypeError: Can't convert 'int' object to str implicitly 

有谁知道如何解决这个问题? 谢谢。

你不能连接一个string与一个int 。 您需要使用str函数将int转换为string ,或使用formatting来设置输出的格式。

更改: –

 print("Ok. Your balance is now at " + balanceAfterStrength + " skill points.") 

至: –

 print("Ok. Your balance is now at {} skill points.".format(balanceAfterStrength)) 

要么: –

 print("Ok. Your balance is now at " + str(balanceAfterStrength) + " skill points.") 

或根据注释使用,将不同的string传递给您的printfunction,而不是使用+连接:

 print("Ok. Your balance is now at ", balanceAfterStrength, " skill points.")