subclass string.Formatter

后端 未结 2 1957
长情又很酷
长情又很酷 2021-01-18 22:39

Following a remark here: How to define a new string formatter, I tried subclassing string.Formatter. Here is what I\'ve done. Unfortunately I seem to have broke

2条回答
  •  一个人的身影
    2021-01-18 23:26

    Good news: you have not done anything wrong. Bad news: that's how string.Formatter behaves, it does not support {}-like positional format. So, the last call will fail even without any subclassing. Good news: that's can be fixed by overriding the parse method:

    import string
    
    class CF(string.Formatter):
        def parse(self, s):
            position = 0
            for lit, name, spec, conv in super(CF, self).parse(s):
                if not name:
                    name = str(position)
                    position += 1
                yield lit, name, spec, conv
    

    Bad news... Ah, no, that's basically it:

    >>> CF().format('{} {}!', 'Hello', 'world')
    'Hello world!'
    

提交回复
热议问题