format sring question

Andrew Dalke adalke at mindspring.com
Fri Sep 3 04:07:06 EDT 2004


Lowell Kirsh wrote:
> In Peter Norvig's Infrequently Answered Questions he explains that the 
> following 2 fnctions look almost identical but are not the same:
> 
> def printf(format, *args): print format % args,
> 
> def printf(format, *args): print str(format) % args,
> 
> The only difference is that in the second one, str(format) replaces 
> format. If args are not given and the format string contains a '%', the 
> first will work but the second will not. Why is this so? It seems to me 
> like '100%' and str('100%) are the same object, no?

The both fail the same way for me; I can't reproduce
a difference.

 >>> def printf1(format, *args): print format % args,
...
 >>> def printf2(format, *args): print str(format) % args,
...
 >>> printf1("100%")
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "<stdin>", line 1, in printf1
ValueError: incomplete format
 >>> printf2("100%")
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "<stdin>", line 1, in printf2
ValueError: incomplete format
 >>>

 >>> printf1("100%%")
100%
 >>> printf2("100%%")
100%
 >>>

My guess is there's supposed to be some sort of
confusing between the trailing ',' when used in a
print statement, to suppress the trailing newline,
and when used to indicate a tuple, as in

   a = args,

to create a single element tuple.  In that case,
  % args, might be a single element tuple where the
first element is the tuple of args.

				Andrew
				dalke at dalkescientific.com



More information about the Python-list mailing list