How to convert Nonetype to int or string?

前端 未结 10 1980
情歌与酒
情歌与酒 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: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.

提交回复
热议问题