9.2. 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 message
has type str):
message - 1
"Hello" / 123
"15" + 2
Interestingly, the +
operator does work with strings, but for
strings, the +
operator represents concatenation, not
addition. Concatenation means joining the two operands by linking
them end-to-end. For example:
1
fruit: str
2
baked_good: str
3
fruit = "banana"
4
baked_good = " nut bread"
5
print(fruit + baked_good)
6
(ch08_add)
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.
Check your understanding
strings-3-1: What is printed by the following statements?
s: str
t: str
s = "python"
t = "rocks"
print(s + t)
You have attempted 1 of 3 activities on this page