On Mon, 29 Jan 2007 23:05:37 -0800, ArdPy wrote: > Hi, > > Pls tell me whats going on in the code snippet below: > >>>> n = 10 >>>> statstr = "N = ",n >>>> type(statstr) #case1 > <type 'tuple'> >>>> print statstr > ('N = ', 10) >>>> print "N = ",n #case 2 > N = 10 > > In the first case the result is printed as a tuple and in the second > it appears as an ordinary string.
The print statement takes one or more comma-delimited objects, and prints each one separated with a space, and then finally prints a newline. If you end the list with a comma, no newline is printed. So when you execute the line: print "N = ", n Python prints "N = ", then a space, then 10, then a newline. Outside of a print statement (and also an "except" statement), commas create tuples. So when you execute the line: statstr = "N = ", n the right-hand side is a tuple with two items. The first item is the string "N = " and the second item is the integer currently named n (in your case, 10). Do not be fooled that brackets make tuples -- they don't. With the exception of the empty tuple () which is a special case, it is commas that make tuples. So these two lines have identical effects: t = 1, 2, 3 t = (1, 2, 3) That is why these two statements print something different: print 1,2,3 print (1,2,3) In the second case, the brackets force the expression "1,2,3" to be evaluated before the print statement sees it, so the print statement sees a single argument which is a tuple, instead of three int arguments. (But notice that the brackets still aren't creating the tuple, the commas are. The brackets just change the order of evaluation.) -- Steven D'Aprano -- http://mail.python.org/mailman/listinfo/python-list