我怎样才能获得回报''如果object [3]返回值是' IndexError:列表索引超出范围'

时间:2016-03-21 04:36:22

标签: python list if-statement

我希望获得'',如果object[3]返回值为IndexError: list index out of range

有可能吗?

我使用的代码是:

object = [4,5]
print(object[3] if object[3] is not None else '')

这个错误是我得到的:

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    object[3] if object[3] is not None else ''
IndexError: list index out of range

1 个答案:

答案 0 :(得分:0)

在访问项目之前检查列表的长度:

>>> lst = [4,5]
>>> lst[3] if len(lst) > 3 and lst[3] is not None else ''
''

>>> lst = [4,5,6,7,8]
>>> lst[3] if len(lst) > 3 and lst[3] is not None else ''
7

BTW,object是内置类型。使用object作为变量会影响它。如果可能,请使用其他名称。