3

I have a string like this:

my_string = '{general_setting} ... {specific_setting}'

The general_setting is the same for the whole program (i.e. database password), whereas the specific_setting can vary throughout the program. Is there a way to format one string twice, first inserting the general_setting and then having a pre-prepared string to insert the specific_setting later?

I'm sure this must have been asked before, but all I could find were questions about how to insert the same VALUE multiple times, not about how to insert different values at different times.

3 Answers3

16

You can have any level of formatting depending on the number of braces

>>> template = '{general_setting} ... {{specific_setting}}'.format(general_setting='general')
>>> my_string = template.format(specific_setting='specific')
>>> print (my_string)
general ... specific
Sunitha
  • 11,422
  • 2
  • 17
  • 22
8

Alternatively, you can use the solution proposed in python format string unused named arguments:

class SafeDict(dict):
    def __missing__(self, key):
        return '{' + key + '}'

then:

>>> '{bond}, {james} {bond}'.format_map(SafeDict(bond='bond'))

returns:

'bond, {james} bond'
relet
  • 6,562
  • 2
  • 31
  • 41
4

Some additions to @Sunitha answer, the first time formatting is {}, second is {{}}, the third time is not {{{}}}, but it is {{{{}}}}.

Four curly braces, because every time you format, the curly braces will be reduced for every place.

Cristian Traìna
  • 8,304
  • 2
  • 35
  • 56
thouger
  • 197
  • 1
  • 7