首页 > 解决方案 > 如何解决 TypeError:只能将 str(不是“types.GenericAlias”)连接到 str

问题描述

我遇到了以下错误:

TypeError:只能将str(不是“types.GenericAlias”)连接到str

此错误反映了什么以及如何解决?

据我记得,我试图将字符串与变量 i 中的表达式相乘,该变量是 for 循环中的迭代变量。但是我再也找不到具体的例子了。我已经注意到该错误,因为我找不到任何示例

标签: pythonerror-handling

解决方案


从错误消息中应该很明显。您不能将字符串连接到其他对象。

'str1' + 'str2'    # OK
'str1' + MyClass() # TypeError

# But, you can also try to cast an object to str
# In this case Python will try to get a result from __str__ method
# And will fallback to __repr__ if __str__ is not defined
'str1' + str(MyClass()) # OK

所以,只连接字符串。


推荐阅读