[Tutor] String formatting question.

Wayne Werner waynejwerner at gmail.com
Wed Mar 30 04:25:14 CEST 2011


On Tue, Mar 29, 2011 at 2:41 PM, Prasad, Ramit <ramit.prasad at jpmchase.com>wrote:

> Is there a difference (or preference) between using the following?
> "%s %d" % (var,num)
> VERSUS
> "{0} {1}".format(var,num)
>

Practically there's no difference. In reality (and under the hood) there are
more differences, some of which are subtle.

For instance, in the first example, var = 3, num = 'hi' will error, while
with .format, it won't. If you are writing code that should be backwards
compatible, pre-2.6, then you should use the % formatting.

My personal preference is to use .format() as it (usually) feels more
elegant:

("{0} "*8+"{1}").format("na", "batman")

vs:

"%s %s" % ("na" * 8, "batman")


And named arguments:

"Name: {name}\nAddress: {address}".format(name="Bob", address="123 Castle
Auuurrggh")

vs

"Name: %(name)\nAddress: %(address)" % {"name": "Bob", "address", "123
Castle Auurgh")


But when I'm dealing with floating point, especially if it's a simple output
value, I will usually use % formatting:

"Money left: %8.2f" % (money,)

vs.

"Money Left: {0:8.2f)".format(money)

Of course, it's best to pick a style and stick to it - having something like
this:

print "Name: %s" % (name)
print "Address: {address}".format(address=street)

is bad enough, but...

print "This is %s {0}".format("horrible") % ("just")

My recommendation would be to use what feels most natural to you. I think I
read somewhere that % formatting is so ingrained that even though the
.format() method is intended to replace it, it's probably going to stick
around for a while. But if you want to be on the safe side, you can always
just use .format() - it certainly won't hurt anything, and the fact that it
says "format" is more explicit. If you didn't know Python, you would know
that "{0} {1} {2}".format(3,2,1) is doing some type of formatting, and since
"Explicit is better than implicit."*, that should be a good thing.

HTH,
Wayne

* see:
import this
this.s.encode('rot13').split('\n')[3]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110329/8a31ed0c/attachment-0001.html>


More information about the Tutor mailing list