Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How come a string multiplied by negative integer results in empty string?

Tags:

python

'0424242' * -5

I understand how multiplying by strings work fundamentally, but I just stumbled on this strange fact that multiplying by negative numbers yields an empty string and thought it was interesting. I wanted to know the deeper why beneath the surface.

Anyone have a good explanation for this?

like image 356
chopper draw lion4 Avatar asked Feb 13 '14 21:02

chopper draw lion4


People also ask

What happens if you multiply a string by an integer?

When you multiply a string by an integer, Python returns a new string. This new string is the original string, repeated X number of times (where X is the value of the integer).

When any string is multiplied with negative number it returns empty string statement is true or false?

Lets see If we multiply a negative number or zero to string then it will return an empty string and the output screen will show No output Let's do it practically now https://code.sololearn.com/csM9wVmZXmMU/?ref=app I hope it helped you.

How do you multiply a string and an integer?

To (properly) multiply an string by an integer, you split the string into characters, repeat each character a number of times equal to the integer, and then stick the characters back together. If the integer is negative, we use its absolute value in the first step, and then reverse the string.

Can we multiply string variable?

No, you can't. However you can use this function to repeat a character.


2 Answers

The docs on s * n say:

Values of n less than 0 are treated as 0 (which yields an empty sequence of the same type as s).

like image 137
ford Avatar answered Oct 12 '22 23:10

ford


What would you expect multiplying a string by a negative integer?

On the other hand

# Display results in nice table
print(keyword1, " "*(60-len(keyword1)), value1)
print(keyword2, " "*(60-len(keyword2)), value2)

without being worried than keyword? be longer than 60 is very handy.

like image 37
Cilyan Avatar answered Oct 12 '22 23:10

Cilyan