Reputation: 1097
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.
Upvotes: 3
Views: 4772
Reputation: 435
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.
Upvotes: 4
Reputation: 7009
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'
Upvotes: 8
Reputation: 12015
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
Upvotes: 17