Edwarric
Edwarric

Reputation: 533

Python: the len() function doesn't recognize 0 at the start

I want to test whether a 10 digit number is of 10 length, but whenever the number begins with 0, len() only counts 9. How can I fix this?

At the moment:

something is a variable made up of numbers, I converted the variable into a string, then made this statement.

if len(something) != 10:
    (do something)

My current code:

number = int(input("Enter number: "))

number = str(number)

if len(number) != 10:
    print ("Not 10 digits long")
else: 
    print ("Good")

If I inputted a number with 10 digits it's fine, BUT, when I input a number with 10 digits and starting with zero, the len() function recognizes the number as 9 long. Help plz

Upvotes: 0

Views: 8526

Answers (3)

user3398633
user3398633

Reputation:

Providing yout code, it's because you are casting your input to int, then casting it down to string (input automatic type is str in Python3, if you're using Python2, don't forget to cast as str or using raw_input like hackaholic).

Replace

number = int(input("Enter number: "))

number = str(number)

By

number = input("Enter number: ")

So number will directly be a string. And you can use len() on it. It even works with 0000000000

Upvotes: 2

jyvet
jyvet

Reputation: 2191

Numbers starting with 0 are represented in base 8 (octal numbers) in python. You need to convert them to string to count their digits :

# Not converted
number1 = 0373451234
print "number: "+str(number1)+" digits:"+str(len(str(number1)))

> number: 65950364 digits:8

# Converted
number2 = "0373451234"
print "number: "+str(number2)+" digits:"+str(len(str(number2)))

> number: 0373451234 digits:10

Upvotes: 0

Hackaholic
Hackaholic

Reputation: 19733

you forcing it to integer, input take values as string

 number = input("Enter number: ")

if len(number) != 10:
    print ("Not 10 digits long")
else: 
    print ("Good")

len function works on string

if you using python 2.x better to use raw_input("Enter Number: ")

Upvotes: 1

Related Questions