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

查看:48
本文介绍了在 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天全站免登陆