Python string formatting when the string contains & ldquo;% s & rdquo; without escaping

advertisements

When formatting a string, my string may contain a modulo "%" that I do not wish to have converted. I can escape the string and change each "%" to "%%" as a workaround.

e.g.,

'Day old bread, 50%% sale %s' % 'today!'

output:

'Day old bread, 50% sale today'

But are there any alternatives to escaping? I was hoping that using a dict would make it so Python would ignore any non-keyword conversions.
e.g.,

'Day old bread, 50% sale %(when)s' % {'when': 'today'}

but Python still sees the first modulo % and gives a:

TypeError: not enough arguments for format string


You could (and should) use the new string .format() method (if you have Python 2.6 or higher) instead:

"Day old bread, 50% sale {0}".format("today")

The manual can be found here.

The docs also say that the old % formatting will eventually be removed from the language, although that will surely take some time. The new formatting methods are way more powerful, so that's a Good Thing.