Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: format string with custom delimiters [duplicate]

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.

like image 237
Don Avatar asked Feb 23 '16 10:02

Don


Video Answer


2 Answers

Using custom placeholder tokens with python string.format()

Context

  • python 2.7
  • string.format()
  • alternative approach that allows custom placeholder syntax

Problem

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

  • string.format() is powerful, but no native support for placeholder delimiter modification.
  • string.format() uses curly-brace which is very common and and causes Delimiter collision
  • string.format() default workaround is to double-up the delimiters, which can be cumbersome.

Solution

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

  • extend native python string.Formatter with custom class
  • configure string.format() to support arbitrary delimiter placeholder syntax
  • permit other enhancements such as custom formatters and filters

Example001: Demo use of a custom ReFormat class

  • we wrote a custom ReFormat class that extends python str.format()
# 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

  • requires extension class to str.format()
  • not intended as a substitute for full-blown sandbox-compatible templating solution
like image 196
dreftymac Avatar answered Sep 17 '22 17:09

dreftymac


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'
}
like image 33
gtlambert Avatar answered Sep 17 '22 17:09

gtlambert