You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何打印ufloat变量名并保留其格式化输出?

解决方案

方法1:利用f-string的!s转换符

直接在{x=}语法中添加!s,强制使用str()格式化ufloat对象,替代默认的repr():

from uncertainties import ufloat

x = ufloat(1.8768768, 0.0039788594)
print(f"{x!s=}")  # 输出: x=1.877+/-0.004

该方法仅需输入一次变量名,代码简洁直接,完全满足需求。

方法2:自定义打印函数(适合批量场景)

如果需要批量处理多个ufloat变量,可封装自动提取变量名的工具函数:

from uncertainties import ufloat
import inspect

def print_ufloat(var):
    # 从调用栈中获取变量名
    caller_locals = inspect.currentframe().f_back.f_locals
    var_name = next(name for name, val in caller_locals.items() if val is var)
    print(f"{var_name}={str(var)}")

x = ufloat(1.8768768, 0.0039788594)
y = ufloat(5.2345, 0.123)
print_ufloat(x)  # 输出: x=1.877+/-0.004
print_ufloat(y)  # 输出: y=5.23+/-0.12

原理说明

Python的{x=}语法默认调用对象的__repr__()方法,而uncertainties库的ufloat对象存在两种格式化逻辑:

  • str(ufloat):返回自动适配有效数字的友好格式(如1.877+/-0.004)
  • repr(ufloat):返回原始精度的底层字符串(如1.8768768+/-0.0039788594)
    通过!s转换符,我们强制f-string使用str()规则格式化变量,从而保留ufloat自带的格式化效果。

内容的提问来源于stack exchange,提问作者Mister Mak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 02:00:09