Reputation: 1534
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
Reputation: 26570
No need to do that. The %s
is a string formatting syntax used for printing. This might help add some more context:
Upvotes: 2
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,
str()
on the passed argument).repr()
on the passed argument).You have the whole list on the documentation.
Upvotes: 0
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 usingstr()
).
Upvotes: 6