gpt4 book ai didi

python - 如何覆盖 python 中的默认字符串格式化程序?

转载 作者:太空宇宙 更新时间:2023-11-03 14:15:51 25 4
gpt4 key购买 nike

有什么方法可以改变 Formatter python 的 string.format() 使用?我有一个自定义的(禁用 check_unused_args 方法),但这需要我使用 formatter.format("text") 语法,而不是 "text ".format() 语法,我更喜欢。

我能以某种方式换掉“默认格式化程序”吗?

注意:这只是一个小项目,我不需要担心弄乱库或任何东西。

最佳答案

Is there some way I can change the Formatter python's string.format() uses?

没有。我认为理性是因为它会导致真正困惑的代码。人们会期望 format_string.format(...) 以一种方式表现,但它会以不同的方式表现,从而导致错误和普遍的悲伤。


但是,您可以显式地告诉 python 您想要使用不同的格式化程序。

class MyFormatter(string.Formatter):
"""This is my formatter which is better than the standard one."""
# customization here ...

MyFormatter().format(format_string, *args, **kwargs)

通过继承 string.Formatter,您可以访问整个 Formatter API,这可以使您的自定义格式化程序更好地工作。

如果这还不够,您可以使用 Formatter 对象调用的 __format__ Hook 方法(包括标准方法)自定义对象格式化自己的方式。

关于python - 如何覆盖 python 中的默认字符串格式化程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33159925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com