现在是时候把所有的打印转换成我正在维护的库中的日志调用了。一些打印调用正在使用str.format
,如下所示(简化):
>>> n = 4000000
>>> print(f"this bird wouldn't voom if you put {n:,} volts through it!")
this bird wouldn't voom if you put 4,000,000 volts through it!
当我试图记录它时:
^{pr2}$这似乎没有正确指定千位分隔符。在使用Python的stdlib日志模块所必需的%-格式语法时,如何指定千位分隔符?在
目前正在使用此解决方案,它确实提供了所需的输出,但似乎是错误的,因为首先使用str.format
格式化变量,然后再次格式化为字符串,而不是直接记录为数字:
>>> log.warning("this bird wouldn't voom if you put %s volts through it!", format(n, ','))
WARNING:root:this bird wouldn't voom if you put 4,000,000 volts through it!
这是
logging
的一个限制,它实际上在documentation中提到过(至少在一个地方):(重点是我的)
但是字符串格式化运算符
%
不支持thousand seperators。在但是,您可以根据官方的
cookbook
修改配方:这实际上是从"Use of alternative formatting styles"部分的最后一个示例逐字复制的(我刚刚更改了消息)。在
就我个人而言,我会接受你的
format(n, ',')
解决方案。它可能并不完美,但不需要设置自定义的LoggerAdapter
来打印不同的千位分隔符。在相关问题 更多 >
编程相关推荐