Python 字符串转 Int 或 None

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18623668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:15:23  来源:igfitidea点击:

Python String to Int Or None

python

提问by user2686811

Learning Python and a little bit stuck.

学习Python,有点卡住了。

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

我正在尝试将一个变量设置为等于,int(stringToInt)或者如果字符串为空设置为None.

I tried to do variable = int(stringToInt) or Nonebut if the string is empty it will error instead of just setting it to None.

我尝试这样做,variable = int(stringToInt) or None但如果字符串为空,它将出错,而不仅仅是将其设置为 None。

Do you know any way around this?

你知道有什么办法解决这个问题吗?

采纳答案by That1Guy

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

如果您想要像您尝试过的单线,请使用以下方法:

variable = int(stringToInt) if stringToInt else None

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

仅当不为空且为“数字”时才会分配variableint(stringToInt)。例如,如果stringToInt'mystring',aValueError将被引发。

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

为了避免ValueErrors,只要您不创建生成器表达式,请使用 try-except:

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

回答by Rob?

Use the fact that it generates an exception:

使用它生成异常的事实:

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

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

这具有绑定variableNone其他常见错误的令人愉快的副作用:stringToInt='ZZTop'例如。

回答by Brian Cain

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)

回答by moliware

I think this is the clearest way:

我认为这是最清晰的方法:

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