Python String to Int Or None

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

    this will parse stringToInt to int if it's valid and return original value if it's '' or None

    variable = stringToInt and int(stringToInt)
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-05 02:25

    I think this is the clearest way:

    variable = int(stringToInt) if stringToInt.isdigit() else None
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题