简体   繁体   English

Python TypeError:“NoneType”类型的对象没有 len()

[英]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).在这种情况下,您传递的参数无论如何都不会引发ValueErrorint(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.

相关问题 Python-TypeError:“ NoneType”类型的对象没有len() - Python - TypeError: object of type 'NoneType' has no len() Python TypeError: (“'NoneType' 类型的对象没有 len()” - Python TypeError: (“object of type 'NoneType' has no len()” Python:TypeError:'NoneType' 类型的对象没有 len() - Python: TypeError: object of type 'NoneType' has no len() TypeError:类型为'NoneType'的对象没有len()python - TypeError: object of type 'NoneType' has no len() python Python错误“ TypeError:类型为'NoneType'的对象没有len() - Python error "TypeError: object of type 'NoneType' has no len() Python 错误 - TypeError:“NoneType”类型的 object 没有 len() - Python error - TypeError: object of type 'NoneType' has no len() Python:TypeError:“NoneType”类型的 object 没有 len():使用 JSON 和 rncryptor - Python: TypeError: object of type 'NoneType' has no len(): Using JSON And rncryptor TypeError:“NoneType”类型的对象在应用程序部署中没有 len() Python - TypeError: object of type 'NoneType' has no len() Python on application deployment Python tkinter TypeError:类型为“ NoneType”的对象没有len() - Python tkinter TypeError: object of type 'NoneType' has no len() Python 错误:“TypeError:“NoneType”类型的 Object 没有 len()” - Python error: “TypeError: Object of type 'NoneType' has no len()”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM