Why do this?

Duncan Booth duncan.booth at invalid.invalid
Thu Oct 5 12:48:36 CEST 2006


"Matthew Warren" <Matthew.Warren at Digica.com> wrote:

> Print "There are "+number+" ways to skin a "+furryanimal
> 
> But nowadays, I see things like this all over the place;
> 
> print("There are %s ways to skin a %s" % (number, furryanimal))
> 
> Now I understand there can be additional formatting benefits when
> dealing with numbers, decimal places etc.. But to me, for strings, the
> second case is much harder to read than the first.
> 

apart from the spurious parentheses you added in the second one, you also 
missed out this variant:

print "There are", number, "ways to skin a", furryanimal

That only works for print though, not for other uses of strings, but it is 
related to the main reason I use format strings instead of concatenation. 

The problem I have with your first option is the large number of times I've 
written:

print "There are"+number+"ways to skin a"+furryanimal

or at least something equivalent to it. If I try to make the same mistake 
with a format string it jumps out to me as wrong:

"There are%sways to skin a%s" % (number, furryanimal)

Also, having a variable of type str called 'number' seems perverse (and 
probably error prone), so I suspect I might need something like:

   print "There are "+str(number)+" ways to skin a "+furryanimal

but the format string does the conversion for free.

The other main reason for preferring format strings is that they make it 
easier to refactor the code. If you ever want to move the message away from 
where the formatting is done then it's a lot easier to extract a single 
string than it is to clean up the concatenation.



More information about the Python-list mailing list