在Python中获取索引的默认值超出范围 [英] Getting a default value on index out of range in Python

查看:157
本文介绍了在Python中获取索引的默认值超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

a=['123','2',4]
b=a[4] or 'sss'
print b

当列表索引超出范围时(此处为'sss'),我想获取默认值.

I want to get a default value when the list index is out of range (here: 'sss').

我该怎么做?

推荐答案

以要求宽恕,而不是允许"的Python精神,这是一种方法:

In the Python spirit of "ask for forgiveness, not permission", here's one way:

try:
    b = a[4]
except IndexError:
    b = 'sss'

这篇关于在Python中获取索引的默认值超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆