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?
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()).
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With