[英]Python TypeError: object of type 'NoneType' has no len()
I am getting an error from this code:我从这段代码中得到一个错误:
def make_int(var):
if len(var) != 0:
var = int(var)
return var
error:错误:
TypeError: object of type 'NoneType' has no len()
How do i fix this?我该如何解决?
It looks like you are trying to avoid a ValueError
when calling int(var)
, but failing to anticipate all the things that could cause one.看起来您在调用int(var)
时试图避免ValueError
,但未能预测可能导致的所有事情。 Don't try;不要尝试; in this case, you are passing an argument that doesn't raise a ValueError
anyway ( int(None)
raises a TypeError
instead).在这种情况下,您传递的参数无论如何都不会引发ValueError
( int(None)
会引发TypeError
)。 Just catch the exception and return var
if it happens.只需捕获异常并在发生时返回var
。
def make_int(var):
try:
return int(var)
except Exception:
return var
use this snippet使用这个片段
def make_int2(var):
if isinstance(var, str) and var.isdigit():
return int(var)
return None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.