为什么会发生这种错误?TypeError:只能将str(而不是“int”)连接到str

2024-05-23 17:09:04 发布

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

这是我的Python代码,我想知道为什么会出现错误

TypeError: can only concatenate str (not "int") to 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? ")

Tags: thetoyougameyouritcanwill
3条回答

您正在尝试将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? ")

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

为此:

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

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

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

因此,使用str()类型转换value1整数变量

str(value1)

快乐编码:)

您希望将字符串与整数连接,但这是不可能的。您应该将整数转换为字符串,如下所示: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/

相关问题 更多 >