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.

1

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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'

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.