How to find where python's string.format(**kwargs) fails?

Viewed 112

I have a long string with many formatting braces and many double braces that are not for format. I also have a dictionary with all the values to be used for formatting. Short example:

text = """There are {n_cats:} cats and {n_dogs:} dogs.
A total of {7}.
Except that there is some {{normal text}}.
"""

kwargs = {'n_cats': 3, 'n_dogs': 4}

print(text.format(**kwargs))

This results in:

Traceback (most recent call last):
    print(text.format(**kwargs))
IndexError: tuple index out of range

And obviously one can see that instead of {7} there should be either 7 or {{7}}. But my real text is much much longer. Is there a way to easily find the place where format() breaks?

1 Answers

Thanks guys. The comments by @Asocia and @chepner gave me the idea which identifies the line in which the problem occurs. We can divide text into lines and apply format to each one of them (having too many keys in kwargs is not a problem). Code:

try:
    print(text.format(**kwargs))
except Exception:
    for (i, t) in enumerate(text.split("\n")):
        try:
            t.format(**kwargs)
        except Exception:
            raise ValueError("Failed in line {:}".format(i+1))
Related