The
operator + can be used on strings, but it’s not addition in the mathematical
sense. The + operator performs concatenation, which means joining the strings
by linking them end-to-end.
>>> fword = 10 >>> sword = 15 >>>print fword+sword 25 >>>fword = ‘10’ >>>sword = ‘15’ >>>print first + second 1015
The
Python interpreter will give you an error if you try to concatenate the
following variable.
>>>fword = 10 >>>sword = ‘15’ >>>print fword+sword Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for +: 'int' and 'str'
The
error means that you can concatenate integers and strings. If you want to
concatenate the strings you have to transform first variable into string. You
can do this by str(fword)
>>>print str(fword)+sword 1015
The
str(variable_name ) transforms the integer into string.
The
string can be transformed into integer using int(variable_name). For example:
>>>print fword + int(sword) 25
Nema komentara:
Objavi komentar