Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error with "len() of unsized object"

Tags:

python

Here's my code:

TestV = int(input("Data: "))
print TestV
print len (TestV)

In fact, it prints TestV but when I try to get its length it gives me the error "len() of unsized object"

I've try something easier like

>>> x = "hola"
>>> print len(x)
4

and it works perfectly. Can anyone explain to me what am I doing wrong?

like image 395
Giancarlo Benítez Avatar asked Feb 18 '15 17:02

Giancarlo Benítez


Video Answer


2 Answers

If you want to count the number of digits, you need to convert it back to a String (note that the minus sign (-) will count as one as well):

len(str(TestV))

Or simply wait with converting it to an int:

TestV = input("Data: ")
print len (TestV)
TestV = int(TestV)

Note however than in the latter case, it will count tailing spaces, etc. as well.

EDIT: based on your comment.

The reason is that strings containing other characters are likely not to be numbers, but an error in the process. In case you want to filter out the number, you can use a regex:

import re

x = input("Data: ")
x = re.sub("\D", "", x)
xv = int(x)
like image 125
Willem Van Onsem Avatar answered Oct 11 '22 12:10

Willem Van Onsem


Type int does not have length.

You are basically turning any input to a type int, in
TestV = int(input("Data: "))

like image 37
taesu Avatar answered Oct 11 '22 10:10

taesu