python - Python中的所有内容都可以转换为字符串吗?

标签 python string casting type-conversion theory

我正在尝试在 Python 中找到一个无法转换为字符串的示例。

>>> str(None)
'None'
>>> str(False)
'False'
>>> str(5)
'5'
>>> str(object)
"<class 'object'>"
>>> class Test:
...     pass
...
>>> str(Test)
"<class '__main__.Test'>"
>>> str(Test())
'<__main__.Test object at 0x7f7e88a13630>'

整个 Python 世界中是否有任何东西不能转换为 str

最佳答案

Is everything in Python castable to a string?

不!

>>> class MyObject():
...     def __str__(self):
...         raise NotImplementedError("You can't string me!")
...
>>> str(MyObject())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __str__
NotImplementedError: You can't string me!

关于python - Python中的所有内容都可以转换为字符串吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62460727/

相关文章:

c# - 在扩展方法中使用显式转换

c - 替换c中给定字符串的字符串的空格

php 类型转换和数组引用

python - Spark k-means OutOfMemoryError 异常

python - 尝试将信息发送到 mysql 数据库时,是否有 python 函数会拆分行?

java - String.intern() 如何工作以及它如何影响字符串池?

python - 如何将字符串转换为时间戳进行比较?

映射的 Groovy AS 关键字 > 类绑定(bind)

python - ASP 脚本中 Python 的 500 服务器错误

python - 为什么这会在第 1 行之后终止?