4

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.

demirod
  • 81
  • 15

1 Answers1

5

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

number = 2
print(f'{1.23456:.{number}f}')
# 1.23
Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53