What happens if i multiply a string by a negative number🤔🤔 | SoloLearn: Learn to code for FREE!

+3

What happens if i multiply a string by a negative number🤔🤔

Ace: Fixed for language tag

7/11/2020 4:41:56 PM

Amith Mathew

9 Answers

New Answer

+12

Note: Next time, tag the language you are asking about or you won't get a good answer to your question. As I see you are learning about and challenging in python, I am assuming you are asking about that language. Now onto your question, The documentation on string * number says that: Values of n less than 0 are treated as 0 (which yields an empty sequence of the same type as s) Basically means that you will always get an empty string for s*-n

+5

I believe a possible behind-the-scenes for the multiplication in question looks like: res="" for i in range(number): res+=string print(res) Since range(number) has nothing when number<=0, res is just a blank.

+5

When in doubt write a small piece of test code to try it out. You will learn, and remember, more from experimenting than you will from someone telling you the answer. "Tell me and I forget, teach me and I remember, involve me and I learn."

+4

Amith Mathew Yeah good question. Multiplying a string by a number is called replication in python. And for replication there are some conditions like 1. One of two data types must be String and the second one must be a Natural number. If we try to replicate a string by multiplying it by an another string then it will throw an error. But what if we multiply it by a negative number. 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. For any querry mention me . Thank you.

+3

Try it. It will not output anything. Like if you multiply a string with 0,it results in "No output". Same case here... It will not output anything

+3

Thank you Prometheus

+2

If you do a = "this" print(a* -2) >>> #prints nothing Same is with *0, *-1, *-2 and so on.

+1

Rishab, Akshay,Ace thanks guys appreciate it

+1

It prints nothing, basically an empty string!