string formatting

MRAB python at mrabarnett.plus.com
Fri May 6 11:29:01 EDT 2011


On 06/05/2011 16:06, Adam Tauno Williams wrote:
> On Fri, 2011-05-06 at 15:58 +0100, MRAB wrote:
>> On 06/05/2011 08:18, Jabba Laci wrote:
>>> Which is the preferred way of string formatting?
>>> (1) "the %s is %s" % ('sky', 'blue')
>>> (2) "the {0} is {1}".format('sky', 'blue')
>>> (3) "the {} is {}".format('sky', 'blue')
>>> As I know (1) is old style. (2) and (3) are new but (3) is only
>>> supported from Python 2.7+.
>>> Which one should be used?
>> I use Python 3, and I tend to use (3), unless I need to use the same
>> value more than once.
>
> I like:
>
> 'my name is {name}'.format(name='Adam')
>
> That makes things clearest, IMO.
>
I wouldn't do that for a short piece of text, but for a much longer
piece of text with multiple values, it does make it a lot clearer.



More information about the Python-list mailing list