In this code snippet:
b = False
print(f'{a if b else ""}')
I would like to use format specifier for a
, eg 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.
如果您使用其中两个,则可以将条件保留在f-string
中,第二个用于a:.2f
print(f'{f"{a:.2f}" if b else ""}')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.