python vs ecmascript

David Bolen db3l at fitlinxx.com
Fri Nov 16 21:42:28 EST 2001


"Peoter Veliki" <peoter_veliki at hotmail.com> writes:

> I'm using Python 2.0 at the moment (it is necessary as it is integrated
> into another product), perhaps this limitation was removed in later
> versions.  If I try to do this:
> 
> print "integer i = " + i
> 
> it will barf on this and tell me that i is not a string, I must do this:
> 
> print "integer i = " + str(i)

As others have pointed out, making i a separate argument to print:

    print "integer i =", i

would let it evaluate it (and automatically stringify it if necessary)
whereas the + operation (which evaluates independently from the print)
is in fact strongly typed and does not perform any automatic
conversion.  Note that in the above, you'll automatically get a space
between the string and i due to how print works, so I removed one
space from the actual string prompt.

One other useful mention is that the "%s" formatter is Python string
formatting operations will automatically apply str() to any non-string
object that it is handed.  So another approach could be:

    print "integer i = %s" % i

and in this approach you have complete control over spacing and what
not since it's all internal to the format string.  Note that
technically the argument to % is a tuple, but for a single argument it
works singly, so you don't have to bother writing (i,).

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list