Python String to Int Or None

后端 未结 5 1795
陌清茗
陌清茗 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:29

    Here are some options:

    Catch the exception and handle it:

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

    It's not really that exceptional, account for it:

       variable = None
       if not stringToInt.isdigit():
           variable = int(stringtoInt)
    

提交回复
热议问题