2

I want to partially format a string in python with some named arguments, but leave any unused or unmatched format specifiers unchanged. For example:

"{} {} {arg1}".format(arg1="hi")
prints:
"{} {} hi"

rather than throwing an IndexError. Or:

"%d %d %(arg1)s" % {'arg1': "hi"}
prints
"%d %d hi"

rather than throwing a TypeError.

Is there some partially hidden corner of the format module that does this (or a option to pass into format())?

I don't have the luxury of creating the format strings myself, they are provided, but I can specify certain fields to be replaced before it is passed upstream. For example, I can specify that if there is one or more %(arg1)s in the string, I will replace it with "hi" before I pass it upstream.

rkh
  • 1,761
  • 1
  • 20
  • 30

0 Answers0