加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

是否有任何对象可以使str()函数在python中抛出错误或异常?

发布时间:2020-12-20 12:09:33 所属栏目:Python 来源:网络整理
导读:我有一个函数,要求输入是一个字符串. 我知道我可以断言或检查输入类型,但我想尽可能地处理它. 我有以下代码来处理它.但我想知道是否有任何情况,这一行可以抛出我需要处理的异常. def foo(any_input): clean_input = str(any_input) # will this throw any ex
我有一个函数,要求输入是一个字符串.

我知道我可以断言或检查输入类型,但我想尽可能地处理它.

我有以下代码来处理它.但我想知道是否有任何情况,这一行可以抛出我需要处理的异常.

def foo(any_input):
    clean_input = str(any_input) # will this throw any exception or error?
    process(clean_input)

解决方法

尝试str深度嵌套列表时,可能会遇到RuntimeError:

>>> x = []
>>> for i in range(100000):
...     x = [x]
... 
>>> y = str(x)
Traceback (most recent call last):
  File "<stdin>",line 1,in <module>
RuntimeError: maximum recursion depth exceeded while getting the repr of a list

或者一个MemoryError试图查找一个巨大的列表:

>>> x = 'a'*1000000
>>> y = [x] * 1000000 # x and y only require a few MB of memory
>>> str(y) # but str(y) requires about a TB of memory
Traceback (most recent call last):
  File "<stdin>",in <module>
MemoryError

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读