Search code examples
pythonstringpython-3.xstring-formatting

Is there a way to format one string multiple times in Python?


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.


Solution

  • 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