If you are using Python 3.2+, use can use str.format_map().
For bond, bond
:
from collections import defaultdict
'{bond}, {james} {bond}'.format_map(defaultdict(str, bond='bond'))
Result:
'bond, bond'
For bond, {james} bond
:
class SafeDict(dict):
def __missing__(self, key):
return '{' + key + '}'
'{bond}, {james} {bond}'.format_map(SafeDict(bond='bond'))
Result:
'bond, {james} bond'
In Python 2.6/2.7
For bond, bond
:
from collections import defaultdict
import string
string.Formatter().vformat('{bond}, {james} {bond}', (), defaultdict(str, bond='bond'))
Result:
'bond, bond'
For bond, {james} bond
:
from collections import defaultdict
import string
class SafeDict(dict):
def __missing__(self, key):
return '{' + key + '}'
string.Formatter().vformat('{bond}, {james} {bond}', (), SafeDict(bond='bond'))
Result:
'bond, {james} bond'