Lesson 01-03: Operators on Strings¶
Not all operators work with strings. In Python, you can only use strings with the +
addition and *
multiplication operators.
Addition with Strings¶
Run the code below. Notice the differences in the two print statements that are run.
print(1 + 3)
print("1" + "3")
print("")
print(1200 + 23)
print("1200" + "23")
(ac_addstring_1)
Great! So notice that there is a clear difference between the two values: 100
and "100"
. That’s because the first is an integer, and the second is a string! The string, when used with addition, will just join them together to be one string.
Using Adding strings will join them together to become one string - this is called string concatenation.
One important thing to note when using string concatenation is that they are combined character for character. That means that if you are combining a first and last name, one of your strings has to have a space, or the result will not have any spaces!
- See the following examples:
"hi" + "there" ==> "hithere"
"hi " + "there" ==> "hi there"
"hi" + " there" ==> "hi there"
"hi " + " there" ==> "hi there"
(note there are two spaces now)
Multiplication with Strings¶
Run the code below.
print(1 * 3)
print("1" * 3)
print("hi" * 5)
print("ha " * 3)
print("hue " * 3 * 2)
(ac_multstring_1)
What can be concluded from your observations from above? Use your observations to predict the next bit of code.
print("hey" * 3 + "there")
Multiplication with strings will just repeat that string. Order of operation still applies - multiplication before addition!
Keep in mind strings still follows your normal order of operations. In the following example:
print("hue " * 3 * 2)
It evalutes "hue " * 3
first, which is "hue hue hue "
. Then it takes that string "hue hue hue "
and multiplies it by 2: "hue hue hue " * 2
- which is "hue hue hue hue hue hue "