How do I handle errors in an f-string?

Viewed 598

I am attempting to handle errors within an f-string, but my attempts don't seem to work. Is there a way to accomplish this?

string = f"For example I thought this syntax would work but it doesn't {try: 5/0 except Exception: str(infinity)}"
2 Answers

You can't. Move the exception handling out of the f-string.

You could try to process whatever you need before composing the fstring and store as a variable, then you could reference the variable in the fstring as below:

from math import inf

try:
    div_by_zero = 5/0
except ZeroDivisionError:
    div_by_zero = str(inf)

my_string = f"Processed outside: {div_by_zero}"
Related