'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?
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).
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.
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.
No, you can't. However you can use this function to repeat a character.
The docs on s * n
say:
Values of n less than
0
are treated as0
(which yields an empty sequence of the same type as s).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With