Operations Involving Strings

When appearing between numbers, the symbols +, -, *, /, and ** perform the relevant arithmetic operations. However, these symbols can sometimes be used to combine instance of data types. We will see examples of this as we introduce new data types. The only one of these symbols that can be used between two strings is the + symbol.

When + is used between two strings, it combines, or concatenates the strings. The string that appears on the left side of + will come first, and the string on the right side will be appended to the end.

a = 'star'
b = 'wars'
c = a + b
print(c)
starwars

We can use + to combine several strings at once. It is not necessary for all of the string values to be stored in variables. We see this in the next example, which places a space between the words “star” and “wars”.

d = a + ' ' + b
print(d)
star wars

Operations Involving Strings and Numbers

If we try to combine a string and a number with +, we will get an error.

print("one" + 2)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-e8bf6f236ab3> in <module>
----> 1 print("one" + 2)

TypeError: can only concatenate str (not "int") to str

Note that numbers enclosed with quotes are also considered strings. Python does not recongnize them as numbers.

print("1" + 2)

Although we are not able to “add” strings to numbers, we are able to “multiply” a string by a number. The result will be a string that has concatenated with itself the specified number of times.

print("blah " * 5)

Since the product of a string and an integer produces another string, expressions of this type can be concatenated together.

print("la " * 4 + "doo " * 3)