Search code examples
pythonstring-lengthnegative-number

why python len() command for "-1" is 2?


for any negative number, it also counts the "-" as a character even though its a part of that number. I tried to make my numbers string first but it won't change the outcome, it always gives +1 to the actual amount of characters involved.

code :

def cube(num):
    return str(num*num*num)
kappa=(cube(-5))
if len(kappa)<4:
    print(kappa)
elif len(kappa)>=4 and len(kappa)>=0:
    print(kappa + "   ,your number is bigger than 999")

outcome :

-125 ,your number is bigger than 999


Solution

  • Because you're taking the length of a string, the minus sign is preserved; that's the logical thing to do, why would we want to remove it? If you're interested in the number of digits, just remove the minus sign before counting the number of chars:

    n = '-125'
    len(str(abs(int(n))))
    => 3