Python String to Int Or None

后端 未结 5 1796
陌清茗
陌清茗 2021-02-05 01:32

Learning Python and a little bit stuck.

I\'m trying to set a variable to equal int(stringToInt) or if the string is empty set to None.

5条回答
  •  渐次进展
    2021-02-05 02:17

    If you want a one-liner like you've attempted, go with this:

    variable = int(stringToInt) if stringToInt else None
    

    This will assign variable to int(stringToInt) only if is not empty AND is "numeric". If, for example stringToInt is 'mystring', a ValueError will be raised.

    To avoid ValueErrors, so long as you're not making a generator expression, use a try-except:

    try:
        variable = int(stringToInt)
    except ValueError:
        variable = None
    

提交回复
热议问题