Float formatting with f-string using a class attribute as parameter

1k Views Asked by At

Is it possible to do something like this?

class P():
    def __init__(self):
        self.digits = 5
        self.pi = f"{np.pi:eval(self.digits)f}"

test = Test()
test.pi

I know that f"{np.pi:5.f}" works, but is it possible to do it with the attribute of a class? Like in a dynamic way? It doesn't needs to use eval(), the importat part is if self.digits can be used in some way.

1

There are 1 best solutions below

1
On BEST ANSWER

you can nest formats inside the format specifier

taking your example and fixing a few things (missing imports, unnecessary numpy, class name mismatch, print the variable instead of just accessing it, dot in front of the number so it limits the decimal places):

import math

class Test():
    def __init__(self):
        self.digits = 5
        self.pi = f"{math.pi:.{self.digits}f}"

test = Test()
print(test.pi)

the output:

$ python3 t.py 
3.14159