Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying a string by zero

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
>>> ''
like image 829
wassimans Avatar asked Dec 01 '13 21:12

wassimans


Video Answer


2 Answers

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.

like image 95
Steve Jessop Avatar answered Oct 27 '22 13:10

Steve Jessop


The * operator is multiplication, the + operator is addition. For numeric types, we would typically expect n*s to be equal to s+s+s+...+s where there are n copies of s in the summation. This illustrates the typical relation between multiplication and addition.

We might expect that multiplication was distributive over addition. That is:

n*s + m*s == (n+m)*s

Now, suppose that m is zero. Then this the distributive rule yields:

n*s + 0*s == (n+0)*x == n*s

And consequently it is clear that 0*s is the additive identity.

For a string, the addition operator is concatenation. And the identity for string concatenation is the empty string. From which we can conclude that 0*s should be defined to be the empty string.

like image 21
David Heffernan Avatar answered Oct 27 '22 13:10

David Heffernan