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