如何用逗号作为千位分隔符记录数字?

2024-05-19 16:25:31 发布

您现在位置:Python中文网/ 问答频道 /正文

现在是时候把所有的打印转换成我正在维护的库中的日志调用了。一些打印调用正在使用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!

Tags: youformatifput记录itthisprint
1条回答
网友
1楼 · 发布于 2024-05-19 16:25:31

这是logging的一个限制,它实际上在documentation中提到过(至少在一个地方):

logging.debug(msg, *args, **kwargs)

Logs a message with level DEBUG on the root logger. The msg is the message format string, and the args are the arguments which are merged into msg using the string formatting operator. (Note that this means that you can use keywords in the format string, together with a single dictionary argument.)

(重点是我的)

但是字符串格式化运算符%不支持thousand seperators。在

但是,您可以根据官方的cookbook修改配方:

import logging

class Message(object):
    def __init__(self, fmt, args):
        self.fmt = fmt
        self.args = args

    def __str__(self):
        return self.fmt.format(*self.args)

class StyleAdapter(logging.LoggerAdapter):
    def __init__(self, logger, extra=None):
        super(StyleAdapter, self).__init__(logger, extra or {})

    def log(self, level, msg, *args, **kwargs):
        if self.isEnabledFor(level):
            msg, kwargs = self.process(msg, kwargs)
            self.logger._log(level, Message(msg, args), (), **kwargs)

logger = StyleAdapter(logging.getLogger(__name__))

def main():
    # this changed
    logger.warning("this bird wouldn't voom if you put {:,} volts through it!", 4000000)

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    main()

WARNING:__main__: this bird wouldn't voom if you put 4,000,000 volts through it!

这实际上是从"Use of alternative formatting styles"部分的最后一个示例逐字复制的(我刚刚更改了消息)。在


就我个人而言,我会接受你的format(n, ',')解决方案。它可能并不完美,但不需要设置自定义的LoggerAdapter来打印不同的千位分隔符。在

相关问题 更多 >