print i + " * " + e + " = " + (i*e) TypeError: unsupported operand type(s) for +: 'int' and 'str'
Perhaps because iand eare not strings? Try it instead print i, '*', e, '=', (i * e).
i
e
print i, '*', e, '=', (i * e)
Your example uses string concatenation (or str.__add__), which only works when both arguments are strings. The operator converts each of its arguments to a string (using the magic method ) and writes the result to standard output, divided by spaces. So, in this case, the numbers and will be converted to strings and written out. print__str__ie
str.__add__
print
__str__
, Python 2.6 print. , .
str . Python .
str
- :
print str(i) + " * " + str(e) + " = " + str(i*e)
, %, :
print "%d * %d = %d" % (i,e,i*e)
, i e .
:
print str(i) + " * " + str(e) + " = " + str((i*e))
, , str() . .
str()
% -, , 2.6, ( ). Personnaly, .
print "{0} * {1} = {2}".format(i, e, i*e)
( 3.1. 3)
PEP : PEP 3101.
EDIT: .
python . :
, i e . str()
- , , , i e . . , ...
, , , :
>>> i = 1 >>> e = 5 >>> print i + " * " + e + " = " + (i*e) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'str' >>> print str(i) + " * " + str(e) + " = " + str(i*e) >>> 1 * 5 = 5
+ . Python . , - : print "% s *% s =% s" % (i, e, * e)... "% d *% d =% d" % (i, e, * e)... "% g *% g =% g" % (i, e, * e)
i, e * e ( string%, numeric/modulo ). . "% s" " str" , % d , % g ( ) ). .
print 'i' + " * " + 'e' + " = " + '(i*e)'
. .
e , .