Python String to Int Or None

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

    Use the fact that it generates an exception:

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

    This has the pleasant side-effect of binding variable to None for other common errors: stringToInt='ZZTop', for example.

提交回复
热议问题