现在已经到了将所有打印转换为我所维护的库中的日志记录调用的时候了。一些打印话费使用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!
当我尝试登录它:
>>> log.warning("this bird wouldn't voom if you put %d, volts through it!", n)
WARNING:root:this bird wouldn't voom if you put 4000000, volts through it!
看来这不是正确指定的千位分隔符。在使用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.Formatter'](https://docs.python.org/3/library/logging.html#logging.Formatter)与'style =“{”' –
So ,也许[这里](https://docs.python.org/3/howto/logging-cookbook.html#use-of-alternative-formatting-styles)会有所帮助。 –
@ juanpa.arrivillaga我已经尝试过,并且无法让它工作。 '{'style用于模板格式本身,但不用于实际消息的参数。但是我可能错过了一些东西 - 如果你能得到它的工作,通过一切手段添加一个答案。 – wim