Home > OS >  Python conditional statements in f-string with format specifiers
Python conditional statements in f-string with format specifiers

Time:05-11

In this code snippet:

b = False
print(f'{a if b else ""}')

I would like to use format specifier for a, e.g. a:.2f. None of these work with Python 3.10:

print(f'{a:.2f if b else ""}')
print(f'{(a:.2f) if b else ""}')
print(f'{{a:.2f} if b else ""}')

What is the solution?


I would like to keep the conditional inside f-string, since there will be a few of them in different places in a multiline string.

CodePudding user response:

You can keep the condition inside the f-string if you use two of them, the 2nd one for the a:.2f

print(f'{f"{a:.2f}" if b else ""}')
  • Related