Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string formatting when string contains "%s" without escaping

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
like image 406
Stephen Gornick Avatar asked May 17 '10 07:05

Stephen Gornick


People also ask

What does %s mean in a Python format string?

%s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string. It is used to incorporate another string within a string. It automatically provides type conversion from value to string. The %s operator is put where the string is to be specified.

What does %s %d mean in Python?

%s is used as a placeholder for string values you want to inject into a formatted string. %d is used as a placeholder for numeric or decimal values.

What is %s and %R in Python?

PythonServer Side ProgrammingProgramming. The %s specifier converts the object using str(), and %r converts it using repr().


3 Answers

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.

like image 141
Tim Pietzcker Avatar answered Oct 11 '22 02:10

Tim Pietzcker


Not really - escaping your % signs is the price you pay for using string formatting. You could use string concatenation instead: 'Day old bread, 50% sale ' + whichday if that helps...

like image 2
psmears Avatar answered Oct 11 '22 03:10

psmears


Escaping a '%' as '%%' is not a workaround. If you use String formatting that is the way to represent a '%' sign. If you don't want that, you can always do something like:

print "Day old bread, 50% sale " + "today"

e.g. not using formatting.

Please note that when using string concatenation, be sure that the variable is a string (and not e.g. None) or use str(varName). Otherwise you get something like 'Can't concatenate str and NoneType'.

like image 2
extraneon Avatar answered Oct 11 '22 01:10

extraneon