'Can't multiply with python [duplicate]

I have this code: (time = 1s)

timeafterchange = time[:-1]
print(timeafterchange*60)

And I get: 111111111111111111111111111111111111111111111111111111111111 (60 characters) and not 60. How can I fix that?



Solution 1:[1]

This happens because you don't have 1, but rather '1', which is a string.

Consider a simple demonstration:

>>> 1 * 5
5
>>> '1' * 5
'11111'

You might try: timeafterchange = int(time[:-1])

Solution 2:[2]

In this case, time is a string. Strings are copied when you use the multiplication operator on them (*), that is why you see the result you described. To fix the issue, call the integer constructor, int(), around the value of timeafterchange so that multiplication behaves like a number. i.e.

timeafterchange = int(time[:-1])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chris
Solution 2