3

I'm maintaining an old Python codebase that has some very strange idioms scattered throughout it. One thing I've come across is string formatting using the percent-encoded style:

'Error %s: %s' % (str(err), str(message))

Ignoring the existence of .format() for modern string interpolation, the question I have is:

Is it necessary to explicitly convert %s parameters with str() or is that exactly what %s does?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Milliams
  • 1,474
  • 3
  • 21
  • 30

3 Answers3

6

No, there is no need for the explicit str() calls, the %s formatter includes a str() call already:

>>> class Foo(object):
...     def __str__(self):
...         return "I am a string for Foo"
... 
>>> '%s' % Foo()
'I am a string for Foo'

This is also explicitly documented in the String Formatting Operations section:

's'
String (converts any Python object using str()).

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

No need to do that. The %s is a string formatting syntax used for printing. This might help add some more context:

What does %s mean in Python?

Community
  • 1
  • 1
idjaw
  • 25,487
  • 7
  • 64
  • 83
0

It depends on the exact specification you use. The old style formatting using a syntax close to that of C lanuage's printf. For instance,

  • %s shows a string (invokes str() on the passed argument).
  • %r shows a representation (invokes repr() on the passed argument).
  • %d takes a number.
  • etc.

You have the whole list on the documentation.

spectras
  • 13,105
  • 2
  • 31
  • 53
  • The wording for `%s` was not ideal, I fixed it. But I explained python would call `str` on it. For the number however, python will only take an integer, you can check it easily: `"%d" % "42"` will raise an exception. – spectras Sep 25 '15 at 12:27