2

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.

0

1 Answer 1

2

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 ""}')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.