Multiplying a string by zero

computer-science, python, string

Solution

Follow the sequence:

'hello' * 3 == 'hellohellohello'
'hello' * 2 == 'hellohello'
'hello' * 1 == 'hello'
'hello' * 0 == ?

An empty string is the only thing that continues the sequence, so it's either that or undefined. It makes sense as "zero repetitions of the string `'hello'`".

This sequence is a way of looking for an inductive definition of string multiplication. We want to define that `s * (n + 1) == (s * n) + s`, and of course we want to define `s * 1 == s`. So when `n == 0` the only value that makes sense for `s * 0` is the empty string.

Mathematically, it's because the empty string `''` is the additive identity. The distributivity property of multiplication is that for any string `s` and non-negative integers `a`, `b`:

s * (a + b) == s * a + s * b

Putting `b == 0`, we see that:

s * a == s * a + s * 0

Hence string multiplication wouldn't be distributive over integer addition unless `s * 0` is the identity value of string addition.

Of course, there's no requirement that just because we call two operators "multiplication" and "addition" then they must be distributive. And in fact string multiplication in Python isn't distributive anyway as soon as negative numbers are involved. But to exclude `0` too by defining `s * 0` as anything else would be rather counter-intuitive.

Problem

In terms of computer science, and specifically in Python, how to explain that multiplying a string by zero (which is an int) produces an empty string? ``` >>> 'hello' * 0 >>> '' ```

Original source