【问题标题】:Float formatting with f-string using a class attribute as parameter使用类属性作为参数使用 f 字符串进行浮点格式化
【发布时间】:2020-10-15 02:15:57
【问题描述】:

有可能做这样的事情吗?

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

test = Test()
test.pi

我知道f"{np.pi:5.f}" 有效,但是可以使用类的属性来实现吗?喜欢以动态的方式?它不需要使用eval(),重要的是self.digits是否可以以某种方式使用。

【问题讨论】:

    标签: python-3.x string-formatting f-string


    【解决方案1】:

    您可以在格式说明符中嵌套格式

    以您的示例并修复一些问题(缺少导入、不必要的numpy、类名不匹配、打印变量而不是仅仅访问它、在数字前加点以限制小数位):

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

    输出:

    $ python3 t.py 
    3.14159
    

    【讨论】:

    • 谢谢@Anthony Sottile,这就是我要找的 :)
    猜你喜欢
    • 1970-01-01
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    相关资源
    最近更新 更多