Python “len() of unsized object”错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28589811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error with "len() of unsized object"
提问by Giancarlo Benítez
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"
事实上,它会打印,TestV
但是当我尝试获取它的长度时,它给了我错误"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?
它完美无缺。谁能向我解释我做错了什么?
采纳答案by Willem Van Onsem
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):
如果要计算数字的数量,则需要将其转换回字符串(请注意,减号 ( -
) 也将计为 1):
len(str(TestV))
Or simply wait with converting it to an int:
或者干脆等待将其转换为 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)
回答by taesu
Type int does not have length.
类型 int 没有长度。
You are basically turning any input to a type int, inTestV = int(input("Data: "))
您基本上是将任何输入转换为 int 类型,在TestV = int(input("Data: "))