Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python conditional statements in f-string with format specifiers

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


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.

>Solution :

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 ""}')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading