Python string formatting when string contains "%s" without escaping
- by Stephen Gornick
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