python - 如何解决 TypeError:只能将 str(不是“types.GenericAlias”)连接到 str
问题描述
我遇到了以下错误:
TypeError:只能将str(不是“types.GenericAlias”)连接到str
此错误反映了什么以及如何解决?
据我记得,我试图将字符串与变量 i 中的表达式相乘,该变量是 for 循环中的迭代变量。但是我再也找不到具体的例子了。我已经注意到该错误,因为我找不到任何示例
解决方案
从错误消息中应该很明显。您不能将字符串连接到其他对象。
'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
所以,只连接字符串。
推荐阅读
- python - 如何在python中创建循环迭代器?
- mysql - MySQL 同一张表中两个查询的一个结果
- xcode - CFBundleIdentifier does not exist on react-native
- c# - asp.net core web api用windows auth扩展认证类型
- python - 为什么我会在尚未关闭的文件中收到“ValueError: I/O operation on closed file”?
- javascript - 从输入创建新网页
- java - 将多个列表合并到一个流中的对象列表?
- docker - 为什么 docker 的可用 cpu 比我设置的限制多?
- algorithm - 数组中满足位方程的对数
- android - Anroid RecyclerView 中的数据绑定不起作用(Kotlin)