TypeError:必须是str,而不是用户输入的类型

时间:2018-05-20 07:51:03

标签: python python-3.x

该脚本应该要求用户定义一个变量然后打印他们输入的内容,并告诉他变量的类型。

xtyped = input("Give me something :\n")
print("You typed :" + xtyped + " and its type is " + type(xtyped))

它会抛出错误:

  

TypeError:必须是str,而不是type

1 个答案:

答案 0 :(得分:1)

通常input的类型始终为str 但是,当你想要进行字符串连接时,它无法连接,因为type(xtyped)type对象而不是str

因此,您需要使用str转换为type(xtyped) str()

xtyped = input("Give me something :\n")
print("You typed : " + xtyped + " and its type is "+ str(type(xtyped)))

输出:

  Give me something :
  hello
  You typed : hello and its type is <class 'str'>