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.
-
ch0103-1: How do you think addition works with Strings?
- (A) It will add them as numbers
- Try running the code again! Each line of output should correspond with the lines of input.
- (B) It will connect them together
- Good job!
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”)
- (A) "John Smith"
- Careful - where do you see a space?
- (B) "JohnSmith"
- Nice job! There's no space in either of the strings, so there's no space in the result either!
- (C) "John" "Smith"
- That is actually two different values. When we combine values we should only have one remaining!
- (D) An error will occur
- No error occurs! :) If you don't believe that, you can always run the code in the activecode box above!
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.
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")
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 "