我可以在引发 ValueError 时显示索引号吗?

问题描述 投票:0回答:2

我想检查给定函数的输入格式,并使用列表列表作为输入。我使用下面的代码来指示输入文件在哪个索引处格式错误:

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 python-3.x valueerror raise
2个回答
1
投票

语法错误。您还没有连接数字。 代码

raise ValueError("The element of input_file at index ' + str(i) + ' is not a list")
基本上仅将
'+ str(i) +'
视为字符串。

试试这个:

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

1
投票

使用双引号 (") 代替单引号 (')

© www.soinside.com 2019 - 2024. All rights reserved.