[Tutor] String formatting question.
Steven D'Aprano
steve at pearwood.info
Thu Mar 31 17:23:18 CEST 2011
Wayne Werner wrote:
> 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.
On the contrary, the two code snippets *explicitly* do different things,
about as different as:
str(var) + str(int(num))
vs.
str(var) + str(num)
The first example expects an arbitrary object and a number on the right
hand side of the % operator. The second example expects two arbitrary
objects. Now, I see from your next comment that you realise this:
> For instance, in the first example, var = 3, num = 'hi' will error, while
> with .format, it won't.
but you don't make it clear that that's because the two pieces of code
ask for two different things, not because of a difference between % and
format(). To be consistent, you would compare:
"%s %s" % (var,num)
vs.
"{0} {1}".format(var,num)
or possibly:
"%s %d" % (var,num)
"{0} {1:d}".format(var,num) # I think, I'm stuck here with Python 2.4
# and can't check it.
Any other differences? Yes, plenty. % formatting and .format() don't
just have different syntax, they have different capabilities. format()
has more power, but that power comes at the cost of being slightly
slower and being more verbose to write.
> 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")
They do different things. The first repeats "na" separated by spaces;
the second has "nanana....na" without spaces.
In any case, we differ in our opinion of elegant, because I feel the two
solutions are equally elegant.
> 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")
The second example will not work, because you have forgotten the type
code. That's an advantage of % formatting: if you forget the type code,
you get an error instead of a default, likely incorrect, type.
> 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.
I should think so... there are plenty of ex-C programmers whose attitude
is "You can have my % format strings when you pry them from my cold,
dead fingers." I'm not a C programmer, and I agree with them.
--
Steven
More information about the Tutor
mailing list