python - 修改python的字符串Formatter

标签 python string

我有一个不接受任何参数并返回一个字符串的函数,我想使用字符串格式调用它。在这里,这是我尝试使用 format 的方式:

def cabbages():
    return 'hello'

In [2]: '{cabbages} world'.format(**locals())
Out[2]: '<function cabbages at 0x101f75578> world'

In [3]: '{cabbages()} world'.format(**locals())
KeyError: 'cabbages()'

所以这两个都不是我想要的,即 cabbages() 的值.

PEP 3101描述了 string.Formatter 的某种方式可以被覆盖,但它似乎没有给出很多例子。如何子类化/自定义字符串 Formatter 类来做这个?

我考虑过的一个hacky 是覆盖__getattr__ cabbages的方法, 而我 真的不想被“认为是病态的”(或者,至少,*那* 病态的)。

最佳答案

我想我在你的回答中看到的主要缺陷是它不能处理原始的复合字段名称语法,如 0.name对于 'getattr'/'dot' 操作符访问也不是,0[name]用于 PEP 3101 中指定的“getitem”检索。

这是一个适用于 Python 2.7 和 3.3 的版本。一个主要的实现差异是它覆盖了 get_value()方法而不是 get_field() .

虽然它如何检测 get_value() 中的调用有点棘手。方法,我不认为它会被认为是病态的。 ;-)

from __future__ import print_function

from string import Formatter

class CallFormatter(Formatter):
    try:  # deal with Py 2 & 3 difference
        NUMERICS = (int, long)
    except NameError:
        NUMERICS = int

    def get_value(self, key, args, kwargs):
        if key.endswith('()'):  # call?
            return kwargs[key[:-2]]()
        elif isinstance(key, self.NUMERICS):
            return args[key]
        else:
            return kwargs[key]

if __name__ == '__main__':
    fmt = CallFormatter()

    def cabbages():
        return 'hello'

    d = dict(name='Fred')

    class Thing(object):
        def __init__(self, value):
            self.attr = value
    th = Thing(42)

    print('d[name]:{d[name]}, th.attr:{th.attr}, '
          'cabbages:{cabbages}'.format(**locals()))
    print(fmt.format('d[name]:{d[name]}, th.attr:{th.attr}, '
                     'cabbages:{cabbages}, cabbages():{cabbages()}', 
                     **locals()))

输出:

d[name]:Fred, th.attr:42, cabbages:<function cabbages at 0x00BB05F0>
d[name]:Fred, th.attr:42, cabbages:<function cabbages at 0x00BB05F0>, 
                          cabbages():hello

关于python - 修改python的字符串Formatter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16752818/

相关文章:

python - AWS IAM Python Boto3 脚本 - 创建用户

python - Python 线程定时器如何在内部工作?

python - 继承调用

python - Z3Python : StringSort support

ios - 如何直接将数组中的所有字符串大写?

python - __file__ 变量是什么意思/做什么?

python - 在使用 Python 请求运行 URL 后,如何从 URL 获取参数?

c - 二维字符串数组的最后一个元素覆盖先前的数组元素

python - 来自两个以上字符串的最长公共(public)单词序列

python - python中的倒逗号和字符串