Home > Blockchain >  Can I show an index number when raising a ValueError?
Can I show an index number when raising a ValueError?

Time:10-19

I want to check the input format for a given function with a list of lists as input. I have used the code below to indicate at which index the input file has the wrong format:

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")

However, the output of this code (with wrong input) is:

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

So, it does not convert str(i) to an actual number. Is it possible to get a number there?

CodePudding user response:

Use double (") instead of single quotes (')

CodePudding user response:

The syntax was wrong. You have not concatenated the numbers. The code raise ValueError("The element of input_file at index ' str(i) ' is not a list") basically considers ' str(i) ' as a string only.

Try this:

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