Lesson 01-03: Operators on Strings

Learning Target: I can use string concatenaiton to combine strings.
Learning Target: I can predict the result of operations 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.

 
1
print(1 + 3)
2
print("1" + "3")
3
print("")
4
print(1200 + 23)
5
print("1200" + "23")
6

(ac_addstring_1)

ch0103-1: How do you think addition works with Strings?



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.

ch0103-2: What will be the result of the following code? print(“John” + “Smith”)





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.

6
 
1
print(1 * 3)
2
print("1" * 3)
3
print("hi" * 5)
4
print("ha " * 3)
5
print("hue " * 3 * 2)
6

(ac_multstring_1)

What can be concluded from your observations from above? Use your observations to predict the next bit of code.

What will be the result of the following code? print("hey" * 3 + "there") Keep in mind the order of operations!


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 "

Next Section - Lesson 01-04: Mixing Datatypes