Python f-string with a Variable Decimal Number Specifier

Viewed 93

Is it possible to use Python f-string with a variable decimal number specifier? Here is an example, but it does not work:

print(f'{1.23456:.2f}')    # working f-string code

number = 2
print(f'{1.23456:.' + number + 'f}')

Python3.7.

1 Answers

You put a second set of brackets inside the first one:

number = 2
print(f'{1.23456:.{number}f}')
# 1.23
Related