You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在抛出ValueError时显示具体索引编号?——列表输入格式校验问题

问题:如何让异常信息显示实际的索引编号?

你正在编写一个函数,需要检查输入是否是列表的列表(list of lists),并且希望在发现格式错误时,在异常信息里明确标记出错误元素的索引。你写了这段代码:

for i, doc in enumerate(input_file):
    if not isinstance(doc,list):
        raise ValueError("The element of input_file at index ' + str(i) + ' is not a list")

但运行后发现,当输入存在错误时,异常信息是这样的:

ValueError: The element of input_file at index ' + str(i) + ' is not a list

str(i)并没有被转换成实际的索引数字,而是直接作为字符串片段显示出来了。


解决方案

问题出在你错误地把字符串拼接的语法写进了引号内部,导致Python没有执行变量替换。这里有几种正确的写法:

  • 方法1:字符串拼接(最基础的写法)
    把字符串拆成三部分,用+连接起来,确保str(i)是Python代码而不是字符串的一部分:

    raise ValueError("The element of input_file at index " + str(i) + " is not a list")
    
  • 方法2:f-string(Python 3.6+推荐)
    这是最简洁直观的写法,直接在字符串前加f,然后用{}包裹变量,Python会自动替换成对应的值:

    raise ValueError(f"The element of input_file at index {i} is not a list")
    
  • 方法3:str.format()方法(兼容性更好)
    如果需要兼容Python 3.6之前的版本,可以用这个方法,把变量放在format()的参数里:

    raise ValueError("The element of input_file at index {} is not a list".format(i))
    

这样修改后,当遇到错误元素时,异常信息就会显示实际的索引编号啦,比如ValueError: The element of input_file at index 3 is not a list。


内容的提问来源于stack exchange,提问作者Emil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 19:52:51