Skip to main content

Section 7.3 Operations on Strings

In general, you cannot perform mathematical operations on strings, even if the strings look like numbers. The following are illegal (assuming that word has been assigned a string value, as in word = "Python"):
word - 1
"Hello" / 123
word * "Hello"
"15" + 2
Interestingly, the + operator does work if both its operands are strings. In that case the + operator represents concatenation, not addition. Concatenation means joining the two operands by linking them end-to-end. For example:
The output of this program is banana nut bread. The space before the word nut is part of the string and is necessary to produce the space between the concatenated strings. Take out the space and run it again, and you’ll see what we mean.
The * operator also works on strings; it performs repetition. For example, 'Fun'* 3 is 'FunFunFun'. One of the operands has to be a string and the other has to be an integer.
This interpretation of + and * makes sense by analogy with addition and multiplication. Just as 4 * 3 is equivalent to 4 + 4 + 4, we expect "Go" * 3 to be the same as "Go" + "Go" + "Go", and it is. Note also in the last example that the order of operations for * and + is the same as it was for arithmetic. The repetition is done before the concatenation. If you want to cause the concatenation to be done first, you will need to use parentheses.
Let’s experiment! In the following activecode area, try to find out these things:
  • With numbers, print(3 + 4) is the same as print(4 + 3). Does it work the same way when concatenating strings? Is print("good" + "bye") the same as print("bye" + "good")?
  • With numbers, print(3 * 4) is the same as print(4 * 3). Does print("ha" * 3) do the same thing as print(3 * "ha")?
  • What happens if you mix strings and numbers with +, as in print(7 + " days")?
  • What happens if you try to multiply strings by strings, as in print("3" * "ha")?

Checkpoint 7.3.1.

    What is printed by the following statements?
    s = "python"
    t = "rocks"
    print(s + t)
    
  • python rocks
  • Concatenation does not automatically add a space.
  • python
  • The expression s + t is evaluated first, then the resulting string is printed.
  • pythonrocks
  • Yes, the two strings are “glued” end to end.
  • Error, you cannot add two strings together.
  • The + operator has different meanings depending on the operands, in this case, two strings.

Checkpoint 7.3.2.

    What is printed by the following statements?
    s = "python"
    excl = "!"
    print(s + excl * 3)
    
  • python!!!
  • Yes, repetition has precedence over concatenation.
  • python!python!python!
  • Repetition is done first.
  • pythonpythonpython!
  • The repetition operator is working on the excl variable.
  • Error, you cannot perform concatenation and repetition at the same time.
  • The + and * operators are defined for strings as well as numbers.