Search code examples
pythonpython-3.xstringf-string

Python f-string with a Variable Decimal Number Specifier


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.


Solution

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

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