using floats/ints in print and write

Grant Edwards grante at visi.com
Mon Aug 20 14:56:47 EDT 2001


In article <9lrm06$ausj5$1 at ID-91520.news.dfncis.de>, Rajarshi Guha wrote:

>   does'nt python 2.2 allow me to use float/int variables in a string 
> context. That is I can't write:
> 
> print a + 'hello'

That's not allowed.  Python has no way of knowing whether to
covert a to string or 'hello' to the type of a.

> where a is float or int. Right now I'm using fpformat.fix() to get a string 
> value. Is there any other way?

If you're familiar with C's printf() you can use the "%"
operator:

>>> "int=%d, float=%5.2f, string='%20s'" % (4,1.234,"foobar")
"int=4, float= 1.23, string='              foobar'"

http://www.python.org/doc/current/tut/node9.html#SECTION009100000000000000000

[That's section 7.1 of the tutorial, just in case the URL
doesn't work for you.]

-- 
Grant Edwards                   grante             Yow!  PARDON me, am I
                                  at               speaking ENGLISH?
                               visi.com            



More information about the Python-list mailing list