Milliams
Milliams

Reputation: 1534

Explicit str() conversion needed for old-style string formatting?

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?

Upvotes: 3

Views: 180

Answers (3)

idjaw
idjaw

Reputation: 26570

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?

Upvotes: 2

spectras
spectras

Reputation: 13542

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.

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1123042

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()).

Upvotes: 6

Related Questions