TypeError: unsupported operand type for +: 'int' and 'str'

print i + " * " + e + " = " + (i*e)

TypeError: unsupported operand type(s) for +: 'int' and 'str'
+5
source share
10 answers

Perhaps because iand eare not strings? Try it instead 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

, Python 2.6 print. , .

+11

str . Python .

- :

print str(i) + " * " + str(e) + " = " + str(i*e)

, %, :

print "%d * %d = %d" % (i,e,i*e)
+11

, i e .

:

print str(i) + " * " + str(e) + " = " + str((i*e))
+5

, , str() . .

% -, , 2.6, ( ). Personnaly, .

print "{0} * {1} = {2}".format(i, e, i*e)

( 3.1. 3)

PEP : PEP 3101.

EDIT: .

+3

python . :

print str(i) + " * " + str(e) + " = " + str(i*e)
0

, i e . str()

0

- , , , i e . . , ...

print str(i) + " * " + str(e) + " = " + str(i*e)
0

, , , :

>>> 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
0

+ . 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 ( ) ). .

0
print 'i' + " * " + 'e' + " = " + '(i*e)'

. .

e , .

 print str(i) + " * " + str(e) + " = " + str(i*e)
-1

All Articles