© 1995-2021 | Dr Anne Dawson All Rights Reserved.
Last updated: Monday 1st March 2021, 12:00 PT, AD
Python's + Operator - How to use with strings and numbers
The plus operator (+) in Python is an operator which has two operands.
For example, in the expression:
2 + 3
the + is the operator
and 2 is an operand and 3 is an operand.
In Python, there are some rules you need to understand about the + operator and its operands:
1) If on the left of the + sign is a string, then on the right of the + sign must also be a string.
According to rule #1, the following line of Python is OK:
print ( "2010 Year Of The " + "Tiger" )
According to rule #1, the following line of Python is ***NOT*** OK:
print ( 2010 + "Year Of The Tiger" )
2) If on the left of the + sign is a number, then on the right of the + sign must be a number.
According to rule #2, the following line of Python is OK:
print ( 2 + 3 )
According to rule #2, the following line of Python is ***NOT*** OK:
print ( 2 + "3" )
Explanation: in the line above, 2 is a number and "3" is a string.
and according to the rules, this is OK:
10 + int("3")
in the line above, the string "3" is converted to the integer (whole number) 3,
and then the integer 3 is added to the integer 10 to make the value 13.
Question 1: What would be the output when this Python line runs:
print ( 10 + int("5"))
Answer: 15
Question 2: What would be the output when this Python line runs:
print ( str(10) + "5")
Answer: 105