How to convert Nonetype to int or string?

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

提交回复
热议问题