[Tutor] data type conversion for print statement

Kent Johnson kent37 at tds.net
Tue Sep 25 19:03:36 CEST 2007

Tim wrote:
> Hello,
> I have a print statement where I use concatenation of variables with "+" to
> avoid extra whitespaces. The variables are mixed (float/int).
> How can I convert them all to strings to have a clean print statement?
> example
> print str(var1)+"and this "+str(var2)+"needs to check "+str(var3)
> how can I convert var1, var2, var3 all at once?

Use string formatting:
print '%sand this %s needs to check %s' % (var1, var2, var3)

The %s format calls str() for its parameter.

> BTW, why does a statment like
> print var1, var2
> automatically add spaces between the variables?

Because it is convenient. Use string formatting to get closer control.


More information about the Tutor mailing list