简体   繁体   中英

In Python 3.8 how to use a variable for print precision

I need to print a float with the precision I read from a file, eg,

float_var = 12.3456
precision_from_file = 2
print(f"float_var: {float_var:.2f}")  ## Using precision_from_file instead of .2f

> output 12.35   , but the .2f came from precision_from_file

Any ideas will be much appreciated.

The answer can easily (embarrassing that I didn't think of it earlier) with f-strings by nesting the precision inside the {variable} curlies.

float_var = 12.3456
precision_from_file = 2
precision_str = '.' + str(precision_from_file) + 'f'
print(f"precision_str ==  {precision_str}")
print(f"float_var:   {float_var:{precision_str}}")

Output:
> precision_str ==  .2f
> float_var:   12.35

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM