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

17

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,777
  • 2
  • 20
  • 23
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,819
  • 2
  • 33
  • 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.

thouger
  • 385
  • 2
  • 8