Exercises#

The focus of these exercises was on string manipulation. First, let us add two strings.

'John went ' + 'for a walk'
'John went for a walk'

The + operator will concatenate these two string objects, merging them into a single string.

Now we will try to subtract one string from another.

'The bird ' - 'that never flew'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-2f8d00f19706> in <module>
----> 1 'The bird ' - 'that never flew'

TypeError: unsupported operand type(s) for -: 'str' and 'str'

This operation is not possible. This is due to the fact there is no logical way that one string may be subtracted from another.

Let’s try adding a string to a floating point number.

'I like to eat ' + 3.14
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-2fff164c0979> in <module>
----> 1 'I like to eat ' + 3.14

TypeError: can only concatenate str (not "float") to str

Again, this raises and error as the there is no way that the Python kernel understands to concatenate a string and a floating point number.

It is possible to multiply two strings?

'Multiplication is ' * 'multiple addition'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-0d995f65bc13> in <module>
----> 1 'Multiplication is ' * 'multiple addition'

TypeError: can't multiply sequence by non-int of type 'str'

It would appear not, again we can understand this as there is no rational to the operation.

However, it is possible to multiply a string by an integer.

'Around the world. ' * 5
'Around the world. Around the world. Around the world. Around the world. Around the world. '

This is because multiplication is essentially multiple addition. So

'Around the world. ' * 10

is equivalent to

'Around the world. ' + 'Around the world. ' + 'Around the world. ' + 'Around the world. ' + 'Around the world. '

Finally, we will consider multiplication of a string by a float.

'Around the world. ' * 8.314
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-5f68f15b5d3f> in <module>
----> 1 'Around the world. ' * 8.314

TypeError: can't multiply sequence by non-int of type 'float'

This gives an error, because as it does not make sense to repeat a string object 8.314 times.