1

I would like to use a variable to specify the number of decimals to format as in this case: (python 3.4.6)

print(str.format('{0:.intVariableName}',1.2345678))
2
  • print(str.format('{0:.3}',1.2345678)) .. works, I would like to use a variable instead of 3. Commented Nov 29, 2018 at 19:07
  • also working: print('{:.{}}'.format(1.2345678, 3)) and print('{:.{var}}'.format(1.2345678, var=3)) - this also omits using explicit indexes for formatting using implicitly order of provided params Commented Nov 29, 2018 at 19:19

1 Answer 1

1

You can use variable name as another argument in format function:

In [29]: print(str.format('{0:.{var}}',1.2345678, var=3))
1.23
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.