How to convert Nonetype to int or string?

前端 未结 10 1982
情歌与酒
情歌与酒 2020-11-29 17:23

I\'ve got an Nonetype value x, it\'s generally a number, but could be None. I want to divide it by a number, but Python raises:

<
相关标签:
10条回答
  • 2020-11-29 18:17

    That TypeError only appears when you try to pass int() None (which is the only NoneType value, as far as I know). I would say that your real goal should not be to convert NoneType to int or str, but to figure out where/why you're getting None instead of a number as expected, and either fix it or handle the None properly.

    0 讨论(0)
  • 2020-11-29 18:20

    I've successfully used int(x or 0) for this type of error, so long as None should equate to 0 in the logic. Note that this will also resolve to 0 in other cases where testing x returns False. e.g. empty list, set, dictionary or zero length string. Sorry, Kindall already gave this answer.

    0 讨论(0)
  • 2020-11-29 18:20

    You should check to make sure the value is not None before trying to perform any calculations on it:

    my_value = None
    if my_value is not None:
        print int(my_value) / 2
    

    Note: my_value was intentionally set to None to prove the code works and that the check is being performed.

    0 讨论(0)
  • 2020-11-29 18:24
    int(value or 0)
    

    This will use 0 in the case when you provide any value that Python considers False, such as None, 0, [], "", etc. Since 0 is False, you should only use 0 as the alternative value (otherwise you will find your 0s turning into that value).

    int(0 if value is None else value)
    

    This replaces only None with 0. Since we are testing for None specifically, you can use some other value as the replacement.

    0 讨论(0)
提交回复
热议问题