【问题标题】:Why does this error happen? TypeError: can only concatenate str (not "int") to str为什么会发生此错误? TypeError:只能将str(不是“int”)连接到str
【发布时间】:2020-01-30 14:23:49
【问题描述】:

这是我的 Python 代码,我想知道错误原因

TypeError: 只能将 str (不是 "int") 连接到 str

正在发生,以及如何解决它:

import random
print("Welcome to the Text adventures Game\nIn this Game you will go on an amazing adventure.")
print("Following are the rules:\n1.You can type the directions you want to go in.\n2. There will be certain items that you will encounter. You can type grab to take it or leave to leave it\n3.In the starting, we will randomly give you 3 values. It is your choice to assign them to your qualites.\nYour Qualities are:\n1.Intelligence\n3.Attack\n4.Defence\n These Qualities will help you further in the game")
print("With these, You are all set to play the game.")
Name=input(str("Please Enter Your Name: "))
a=input("Hi "+Name+", Ready To Play The Game?: ")
Intelligence=0
Attack=0
Defence=0
if a=="yes"or a=="y":
    value1=random.randint(0,100)
    choice1=input("Your Value is: \n"+value1+ "\nYou would like to make it your Intelligence,Attack Or Defence level? ")

【问题讨论】:

  • 将您的整数变量类型转换为 str。像这样str(value1)

标签: python


【解决方案1】:

您正在尝试将int 添加到string

试试这个

if a=="yes"or a=="y":
    value1=random.randint(0,100)
    choice1=input("Your Value is: \n"+str(value1)+ "\nYou would like to make it your Intelligence,Attack Or Defence level? ")

【讨论】:

    【解决方案2】:

    发生这种情况是因为存储在变量中的值是一个整数,并且您将它连接在字符串之间。

    这样做:----

    使用 str() 方法: str() 函数返回给定对象的字符串版本。 它在内部调用对象的__str__() 方法。

    如果找不到__str__() 方法,则改为调用repr(obj)。

    repr() 的返回值 repr() 函数返回给定对象的可打印表示字符串。

    所以用 str() 对 value1 整数变量进行类型转换。

    str(value1)
    

    编码愉快:)

    【讨论】:

      【解决方案3】:

      您想将一个字符串与一个整数连接起来,但这是不可能的。您应该将整数转换为字符串,如下所示:str(value1)

      但是,使用字符串的.format() 方法效率更高。此方法自动将整数类型转换为 str。

      在你的情况下:

      choice1=input("Your Value is: \n{}\nYou would like to make it your Intelligence,Attack Or Defence level? ".format(value1))
      

      或者如果你使用Python 3.6+,格式化的字符串也是可用的。开头的f 字符表示格式化的字符串。

      在你的情况下:

      choice1=input(f"Your Value is: \n{value1}\nYou would like to make it your Intelligence,Attack Or Defence level? ")
      

      您可以在此页面上找到几种 Python 字符串格式:https://realpython.com/python-string-formatting/

      【讨论】: