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. 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
use this snippet
def make_int2(var):
if isinstance(var, str) and var.isdigit():
return int(var)
return None
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.