-2

I have a number that is represented as a string. I need to multiply this number by -1.

        myvalue = htmlcontent.find_next(class_='floatRight').text
        print(myvalue)
        myvalue = myvalue * -1
        print(myvalue)

The above outputs the following:

-0.1234

The second print doesn't display anything. What am I doing wrong?

4thSpace
  • 43,672
  • 97
  • 296
  • 475
  • Cast the string to a float – Jared Smith Oct 24 '18 at 15:27
  • Multiplying a string won't multiply by value, but the actual string. `"moo" * 2` will become `moomoo`. Hence, doing a negative multiplication will subtract all of the string. Much like doing `"moo" * 0` will produce a zero length string. if you're from a JavaScript background, this might be confusing because of automated lazy operations. But here, you will at least need to re-cast the variable type when doing such operations. – Torxed Oct 24 '18 at 15:29
  • Just use the debugger and see what's the content first! :/ – pierpytom Oct 24 '18 at 15:29
  • `int(myvalue)*-1` – Rohit-Pandey Oct 24 '18 at 15:29

1 Answers1

6

Short answer: float(myvalue) * -1.

You're trying to multiply a string with some number. Multiplying a string (say s) with a number (say n) will concatenate the same string n times. And if n is less than or equal to 0, then it'll return an empty string.

You're multiplying your string by -1, that's why you're getting an empty string. If you multiply it with 2, you'll get -0.1234-0.1234.

Ahmad Khan
  • 2,655
  • 19
  • 25