Python String to Int Or None

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

    I think this is the clearest way:

    variable = int(stringToInt) if stringToInt.isdigit() else None
    

提交回复
热议问题