Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

string formatting

44 views
Skip to first unread message

Jabba Laci

unread,
May 6, 2011, 3:18:17 AM5/6/11
to Python mailing list
Hi,

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?

Laszlo

Message has been deleted

Steven D'Aprano

unread,
May 6, 2011, 4:46:04 AM5/6/11
to
On Fri, 06 May 2011 10:00:30 +0200, Web Dreamer wrote:

> Jabba Laci a écrit ce vendredi 6 mai 2011 09:18 dans
> <mailman.1229.1304666...@python.org> :

> According to python's documentation, (3) and (2) are preferred and (1)
> is deprecated.

I think you are wrong, % formatting is not deprecated. Do you have a link
showing otherwise?


[steve@sylar ~]$ python3.2
Python 3.2a1 (r32a1:83318, Aug 12 2010, 02:17:22)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import warnings
>>> warnings.simplefilter("always")
>>> "%d" % 42
'42'


I see no DeprecationWarning.

--
Steven

Chris Rebert

unread,
May 6, 2011, 5:23:19 AM5/6/11
to Steven D'Aprano, pytho...@python.org
On Fri, May 6, 2011 at 1:46 AM, Steven D'Aprano
<steve+comp....@pearwood.info> wrote:
> On Fri, 06 May 2011 10:00:30 +0200, Web Dreamer wrote:
>> Jabba Laci a écrit ce vendredi 6 mai 2011 09:18 dans
>> <mailman.1229.1304666...@python.org> :
>>> Hi,
>>>
>>> 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?
>>
>> According to python's documentation, (3) and (2) are preferred and (1)
>> is deprecated.
>
> I think you are wrong, % formatting is not deprecated. Do you have a link
> showing otherwise?

I'm not them, but:
"Note: The formatting operations described here [involving %] are
obsolete and may go away in future versions of Python. Use the new
String Formatting [i.e. format()] in new code."
http://docs.python.org/dev/library/stdtypes.html#old-string-formatting-operations

Technically, not formally deprecated, but such a characterization
isn't too far off the mark either.

Cheers,
Chris
--
http://rebertia.com

Message has been deleted

nn

unread,
May 6, 2011, 9:06:46 AM5/6/11
to
On May 6, 8:10 am, Web Dreamer <webdrea...@nospam.fr> wrote:
> Chris Rebert a écrit ce vendredi 6 mai 2011 11:23 dans
> <mailman.1230.1304673808.9059.python-l...@python.org> :

>
>
>
> > I'm not them, but:
> > "Note: The formatting operations described here [involving %] are
> > obsolete and may go away in future versions of Python. Use the new
> > String Formatting [i.e. format()] in new code."
> >http://docs.python.org/dev/library/stdtypes.html#old-string-formatting-
> operations
>
> > Technically, not formally deprecated, but such a characterization
> > isn't too far off the mark either.
>
> Thanks Chris for the link.
>
> Indeed, They mention:
>
> "The formatting operations described here are obsolete and may go away in
> future versions of Python. Use the new String Formatting in new code."
>
> So the proper word is "obsolete" and in my mind I remembered "deprecated"
> since they say it could be removed from future versions of python.
>
> So I should have said "obsolete".
>
> What I would like to know is the difference between "deprecated" and
> "obsolete"...
>
> --
> Web Dreamer

In this context I think obsolete means: Will be removed in some
undetermined version in the future; 3 versions or more from now.
There is also pending deprecation: Will be (usually) removed in the
version after the next. And
deprecated: Will be removed in the next version.

Steven D'Aprano

unread,
May 6, 2011, 10:24:56 AM5/6/11
to

Not deprecated at all. In context, deprecation *is* a formal process.

In any case, on occasions that the issue has been raised, there has been
considerable community objection to removal of % formatting. Guido might
want to remove it, but I wouldn't bet on it happening before Python 4000.

It's perfectly safe to continue using % formatting, if you choose.

--
Steven

Steven D'Aprano

unread,
May 6, 2011, 10:33:01 AM5/6/11
to
On Fri, 06 May 2011 14:10:17 +0200, Web Dreamer wrote:

> What I would like to know is the difference between "deprecated" and
> "obsolete"...


Writing x*x instead of x**2 is obsolete, but it will never go away.

Writing apply(func, args) instead of func(*args) is deprecated. It has
gone away.

Obsolete is a value judgment you are welcome to ignore. Deprecation is a
formal process that warns you that your code *will* break in the future.

--
Steven

MRAB

unread,
May 6, 2011, 10:58:19 AM5/6/11
to pytho...@python.org
On 06/05/2011 08:18, Jabba Laci wrote:
> Hi,
>
> 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.

Adam Tauno Williams

unread,
May 6, 2011, 11:06:13 AM5/6/11
to pytho...@python.org

I like:

'my name is {name}'.format(name='Adam')

That makes things clearest, IMO.

MRAB

unread,
May 6, 2011, 11:29:01 AM5/6/11
to pytho...@python.org
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.

harrismh777

unread,
May 6, 2011, 3:22:25 PM5/6/11
to
Steven D'Aprano wrote:
> It's perfectly safe to continue using % formatting, if you choose.
>

I would hope so, since its the way in most of the books, much of the
doc and a majority of the code...

I don't really like the old style, not because there is anything
wrong with it, because its an obvious carry-over from the cryptic
formatting style of 'C' printf(), and others. It seems to me that the
purpose of formatting is to make output clear, and therefore the output
formatting style itself should be clear and clean.
On the other hand, among the three styles listed by the OP

(1) "the %s is %s" % ('sky', 'blue')

(2) "the {0} is {1}".format('sky', 'blue')

(3) "the {} is {}".format('sky', 'blue')

... they all *feel* good... I mean, they're all clear, clean,
precise...

On the other hand, while any 'C' programmer is able to see instantly
that (1) is a some type of formatting construct, (2) & (3) are clear and
obvious formatting constructs, even for newbies and esp. for non 'C'
programmers.

On the other hand, at this point, it seems that this is personal
preference issue completely. So, if the book says you can do it, and
there is no formal deprecation process in the works, feel free to
express yourself with the style that best suits 'you'.

On the other hand,..... :)

kind regards,
m harris

harrismh777

unread,
May 6, 2011, 3:39:15 PM5/6/11
to
harrismh777 wrote: OP wrote:

> (1) "the %s is %s" % ('sky', 'blue')
>
> (2) "the {0} is {1}".format('sky', 'blue')
>
> (3) "the {} is {}".format('sky', 'blue')

On the other hand, consider this 3.x code snip:

print("the %s is %d" % ('sky', 'blue'))


That formatting will throw an exception, because the format
construct is restricting the format entry to be a number, which 'blue'
clearly isn't....

The following print() is better, because *any* time or *most* types
can be substituted and the 'polymorphism' of Python kicks in allowing
for that, as so:

print("the {} is {}".format('sky', 3.4))

print("the {} is {}".format('sky', 'blue'))


l=['cloudy', 'today']
print("the {} is {}".format('sky', l))


On the other hand,.... :)


kind regards,
m harris

Neil Cerutti

unread,
May 6, 2011, 3:54:14 PM5/6/11
to
On 2011-05-06, harrismh777 <harri...@charter.net> wrote:
> Steven D'Aprano wrote:
>> It's perfectly safe to continue using % formatting, if you
>> choose.
>
> I would hope so, since its the way in most of the books, much
> of the doc and a majority of the code...
>
> I don't really like the old style, not because there is
> anything wrong with it, because its an obvious carry-over from
> the cryptic formatting style of 'C' printf(), and others. It
> seems to me that the purpose of formatting is to make output
> clear, and therefore the output formatting style itself should
> be clear and clean.

C's printf is a venerable example of the power of notation.
Notation kicks ass. Another that's well known are regular
expressions. Python uses this powerful idea again in the struct
module. Any other places?

Functions and classes are a general purpose, though verbose, form
of notation and can be used in place of mini languages when you
don't want to bother, e.g., C++'s iostreams, and pyparsing's
grammar declarations.

Lisp declared that you could implement mini-languages in Lisp,
rather than just parsing them.

Python 3's format notation is an improvement for Python, since
Python doesn't need the type information that's crucial for C and
particularly scanf, an application of C's mini-language that
Python doesn't need. Delimiting the escape sequences also makes
it easier to read and parse complex formating declarations.

For simple constructs there's not much difference between them,
but if you switch to .format you'll probably reap some benefit.

--
Neil Cerutti

Ian Kelly

unread,
May 6, 2011, 3:54:52 PM5/6/11
to harrismh777, pytho...@python.org
On Fri, May 6, 2011 at 1:39 PM, harrismh777 <harri...@charter.net> wrote:
> harrismh777 wrote:    OP wrote:
>
>> (1) "the %s is %s" % ('sky', 'blue')
>>
>> (2) "the {0} is {1}".format('sky', 'blue')
>>
>> (3) "the {} is {}".format('sky', 'blue')
>
>   On the other hand, consider this 3.x code snip:
>
>   print("the %s is %d" % ('sky', 'blue'))
>
>
>   That formatting will throw an exception, because the format construct is
> restricting the format entry to be a number, which 'blue' clearly isn't....

If you used %d, then that exception is presumably what you wanted. If
not, then you should just do:

print("the %s is %s" % ('sky', 'blue'))

>   The following print() is better, because *any* time or *most* types can be
> substituted and the 'polymorphism' of Python kicks in allowing for that, as
> so:

'%s' has exactly the same degree of polymorphism as '{}', because both
simply call str() on their argument. There are good reasons to use
format instead of % if possible, but polymorphism isn't one of them.

Terry Reedy

unread,
May 6, 2011, 4:54:17 PM5/6/11
to pytho...@python.org
On 5/6/2011 3:22 PM, harrismh777 wrote:

> I don't really like the old style, not because there is anything wrong
> with it,

There is in that it special cases tuples. For instance, a message
function like

def emsg(x):
print("The following object caused a proplem: %s" % x)

raises "TypeError: not all arguments converted during string formatting"
if x is a tuple with other than 1 member and extracts x[0] if there is
just one. Neither is the desired behavior. That has been a problem (and
sometimes a debugging puzzle) in real code One has to remember to write
something like

def emsg(x):
if isinstance(x,tuple):
x = (x,)
print(The following object caused a proplem: %s" % x)

Guido sees that his original design is a bit of a bug trap, which is one
reason he wanted to replace it.

--
Terry Jan Reedy

Chris Angelico

unread,
May 6, 2011, 8:09:49 PM5/6/11
to pytho...@python.org
On Sat, May 7, 2011 at 6:54 AM, Terry Reedy <tjr...@udel.edu> wrote:
> def emsg(x):
>  if isinstance(x,tuple):
>    x = (x,)
>  print(The following object caused a proplem: %s" % x)
>

Couldn't you just do that unconditionally?
print(The following object caused a proplem: %s" % (x,))

Chris Angelico

Steven D'Aprano

unread,
May 6, 2011, 10:30:53 PM5/6/11
to
On Fri, 06 May 2011 14:39:15 -0500, harrismh777 wrote:

> On the other hand, consider this 3.x code snip:
>
> print("the %s is %d" % ('sky', 'blue'))
>
>
> That formatting will throw an exception, because the format
> construct is restricting the format entry to be a number, which 'blue'
> clearly isn't....

Er, yes. That's clearly deliberate, because the target uses %d rather
than %s. If the author wanted to accept anything, she would used %r or %s.

You might as well argue that:

print("the {} is {}".format('sky', int(x)))

is wrong, because if you leave the int out, any object can be used.


> The following print() is better, because *any* time or *most* types
> can be substituted and the 'polymorphism' of Python kicks in allowing
> for that, as so:
>
> print("the {} is {}".format('sky', 3.4))


This is not comparing apples with apples. The format equivalent is:

print("the {} is {:d}".format('sky', 'blue'))

which will also raise an exception, ValueError instead of TypeError.

--
Steven

Terry Reedy

unread,
May 7, 2011, 3:55:01 AM5/7/11
to pytho...@python.org

I guess so, as long as one remembers the ','. That does not obviate the
fact that % x is an attractive nuisance which works until it does not.

--
Terry Jan Reedy

alex23

unread,
May 9, 2011, 1:47:04 AM5/9/11
to
harrismh777 <harrismh...@charter.net> wrote:
> [...] because *any* time or *most* types

> can be substituted and the 'polymorphism' of Python kicks in allowing
> for that [...]

The same benefit one might get from using the idiomatic 'if not
list:'?

;)

Message has been deleted

Chris Angelico

unread,
May 10, 2011, 10:43:33 AM5/10/11
to pytho...@python.org
On Wed, May 11, 2011 at 12:15 AM, Web Dreamer <webdr...@nospam.fr> wrote:
> I was unsure of the difference between deprecated and obsolete.
>
> So now, if I understand well, obsolete comes before deprecated, such that if
> a feature is obsolete it will be deprecated in an unknown future, after
> which it will be removed once it has been deprecated (a certain time after
> it was rendered obsolete)?
> (might need an aspirin to read that one :-) )
>
> So If I'm right, old string formatting "could" one day be deprecated but it
> is not yet?

I wouldn't say that obsolete features "will be" deprecated. That
expression makes little sense (I know, for I have seen it in eBay's
API documentation, and it did not fill me with joy). Deprecation is
(usually) a formal procedure that clearly states that a feature should
not be used. It may be accompanied by a strict cutoff ("will be
removed in version X"), or just left vague, but linting tools can
identify all use of deprecated features.

Obsolete, however, is simply a description. Sopwith Camels were
obsolete in the second world war, and VHS has been obsoleted by
optical disc media. However, if you wish to fly a Camel or play a VHS,
nothing's stopping you. The sky will still accept your Camel, and your
VHS player will still talk to your television. (The analogy breaks
down a bit in that your obsolete VHS player may be using a deprecated
cabling style, but it's coax that's deprecated, not VHS.) There's no
"projected end date" for them.

Generally, a feature is obsolete before it's deprecated, but
technically that's not a requirement, and API designers can sometimes
be quite arbitrary. On the other hand, obsolescence is quite informal,
and people can disagree about whether or not something is. (Hi Ken,
your continued use of inches is noted. Thank you.)

Chris Angelico

Raymond Hettinger

unread,
May 10, 2011, 1:20:27 PM5/10/11
to


Sometimes, I use both ;-)
That can save you from ugly escapes such as %%s or {{0}}.

Here's an example from the standard library:
http://hg.python.org/cpython/file/7254c03b7180/Lib/collections.py#l235

Note the template has both {typename} formatting for the first pass
and %r style formatting in the generated code.

Raymond

------------
follow my tips and recipes on twitter: @raymondh

0 new messages