pythonsyntaxformatstring-interpolationcheetah

Python: format string with custom delimiters


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.


Solution

  • Using custom placeholder tokens with python string.format()

    Context

    Problem

    We want to use custom placeholder delimiters with python str.format()

    Solution

    We write a custom class that extends native python str.format()

    Example001: Demo use of a custom ReFormat class

    # import custom class
    import ReFormat
    
    # prepare source data
    odata = { "fname" : "Planet",
              "lname" : "Earth",
              "age"   : "4b years",
             }
    
    # format output using .render() 
    # method of custom ReFormat class
    #
    vout = ReFormat.String("Hello <%fname%> <%lname%>!",odata).render()
    print(vout)
    

    Pitfalls