我的函数将字符串拆分为行,检查第 index 行,并返回两个值之一。这是一个简化版本:
def f(text, index):
rows = text.split('\n')
row = rows[index] # <-- IndexError thrown here.
if row_meets_some_condition:
return "Yes"
else:
return "No"
调用者有时会传递一个负值index
(当他想使用基于文件结尾的索引时),这工作正常,除非text
行太少,在这种情况下我会得到IndexError
一个row = rows[index]
。
除了捕获错误之外,是否有一种惯用的方法来检查是否index
是合法索引?rows