Python: format string with custom delimiters

Don picture Don · Feb 23, 2016 · Viewed 8.9k times · Source

EDITED

I have to format a string with values from a dictionary but the string already contains curly brackets. E.g.:

raw_string = """
    DATABASE = {
        'name': '{DB_NAME}'
   }
"""

But, of course, raw_string.format(my_dictionary) results in KeyErro.

Is there a way to use different symbols to use with .format()?

This is not a duplicate of How can I print literal curly-brace characters in python string and also use .format on it? as I need to keep curly brackets just as they are and use a different delimiter for .format.

Answer

gtlambert picture gtlambert · Feb 23, 2016

I don't think it is possible to use alternative delimiters. You need to use double-curly braces {{ }} for curly braces that you don't want to be replaced by format():

inp = """
DATABASE = {{
    'name': '{DB_NAME}'
}}"""

dictionary = {'DB_NAME': 'abc'}
output = inp.format(**dictionary)
print(output)

Output

DATABASE = {
    'name': 'abc'
}