String Operations

And we can do some of the same things with variables that have string values.

Let's create two more variables:

>>> colour = "yellow"

>>> day = "Monday"

The first thing we'll do is put them together with a plus sign. Do you remember what the plus sign does for strings? It concatenates them.

>>> colour + day

And what happens if we multiply a variable with a string value by a variable with a number value?

>>> colour * fishes

Now let's look at this expression where we add and multiply. What do you think Python will return here? Let's type this at our prompt and find out:

>>> colour + day * fishes

Did you get the answer you expected? Okay, let's break this down and see what happened.

Our expression is color plus day times fishes. We know that color is yellow, day is Monday, and fishes is three.

So when we asked Python to calculate - or evaluate - this expression, what did it return? Let's take a look:

>>> colour + day * fishes

'yellowMondayMondayMonday'

You might have been expecting Python to concatenate colour and day first, and then multiply those strings times three.

Do you remember when we talked about order of operations earlier? Maybe not? Okay, let's recap.

Order of operations is a rule that determines which parts of an expression are calculated first. In most programming languages, multiplication is always done before adding or subtracting. So in this case, Python did the multiplication side of the operation first - so you got the word 'Monday' times 3 - and then concatenated that with the word 'yellow'.

But if you wanted the addition to be done first, there is a different way you could write this expression. You could put parentheses around "colour + day".

>>> (colour + day) * fishes

This way, Python knows that it needs to concatenate "yellow" and "Monday" first, and then multiply the whole thing by three:

>>> (colour + day) * fishes

'yellowMondayyellowMondayyellowMonday'

Answers

>>> colour + day

'yellowMonday'

>>> colour * fishes

'yellowyellowyellow'