You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python脚本打印输入内容及类型时报TypeError: must be str, not type错误求助

解决Python字符串拼接时的TypeError问题

嘿,这个问题我太熟悉啦!咱们来快速拆解一下:

错误原因

你遇到的 TypeError: must be str, not type 是因为 type(xtyped) 返回的是一个类型对象(比如输入字符串时会返回 <class 'str'>),而不是字符串类型。Python里不能直接用 + 把类型对象和普通字符串拼接,所以就触发了这个错误。

修正方案

这里有两种简单的解决办法,按需选择:

方法1:用str()转换类型对象为字符串

把 type(xtyped) 用 str() 包裹,强制转换成字符串后再拼接:

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

方法2:使用f-string(推荐,更简洁)

Python 3.6及以上版本支持f-string,它会自动帮你把对象转换成字符串,代码可读性更高:

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

额外优化:只显示类型名称

如果不想输出 <class 'str'> 这种完整格式,只想显示类型名称(比如str),可以用 type(xtyped).__name__:

xtyped = input("Give me something :\n")
print(f"You typed :{xtyped} and its type is {type(xtyped).__name__}")

这样输入"hello"的话,输出会是:You typed :hello and its type is str,看起来更清爽。

内容的提问来源于stack exchange,提问作者takiskan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:04:52