0

我从这段代码中得到一个错误:

def make_int(var):
    if len(var) != 0:
        var = int(var)
    return var

错误:

TypeError: object of type 'NoneType' has no len()

我该如何解决?

4

2 回答 2

-1

使用这个片段

def make_int2(var):
    if isinstance(var, str) and var.isdigit():
        return int(var)
    return None
于 2020-11-19T18:53:24.400 回答
-1

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
于 2020-11-19T18:45:09.563 回答