Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 889
Milliams Avatar asked Jan 25 '26 17:01

Milliams


2 Answers

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

like image 191
Martijn Pieters Avatar answered Jan 28 '26 07:01

Martijn Pieters


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?

like image 29
idjaw Avatar answered Jan 28 '26 07:01

idjaw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!