proposal to allow to set the delimiter in str.format to something other than curly bracket

Peter Otten __peter__ at web.de
Mon Apr 4 18:18:08 CEST 2011


Alia Khouri wrote:

> Terry Reedy wrote:
> 
>> Just double the brackets, just as one doubles '\\' to get '\' in a
>> string.
>>
>> >>> "class {0}Model {{ public bool IsModel(){{ returntrue;
>> }}}}".format('My')
>>
>> 'class MyModel { public bool IsModel(){ returntrue; } }'
>>
> 
> Indeed, I tried that, but it means I have to double bracket all the
> csharp code which just creates more work for me.

You could automatically convert from a custom format like that in your 
original post:

import re

_lookup = {
    "[[": "{",
    "]]": "}",
    "{": "{{",
    "}": "}}",
}

def _substitute(m):
    return _lookup[m.group()]

def custom_format(template, *args, **kw):
    return (re.compile(r"\[\[|]]|\{|\}")
            .sub(_substitute, template)
            .format(*args, **kw))

code = "class [[0]]Model { public bool IsModel(){ return a[42] || true; } }"
print custom_format(code, "My")





More information about the Python-list mailing list