我从这段代码中得到一个错误:
def make_int(var):
if len(var) != 0:
var = int(var)
return var
错误:
TypeError: object of type 'NoneType' has no len()
我该如何解决?
使用这个片段
def make_int2(var):
if isinstance(var, str) and var.isdigit():
return int(var)
return None
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. Don't try; in this case, you are passing an argument that doesn't raise a ValueError anyway (int(None) raises a TypeError instead). Just catch the exception and return var if it happens.
def make_int(var):
try:
return int(var)
except Exception:
return var