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
Python String to Int Or None
提问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 None
but 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 variable
to int(stringToInt)
only if is not empty AND is "numeric". If, for example stringToInt
is 'mystring'
, a ValueError
will be raised.
仅当不为空且为“数字”时才会分配variable
给int(stringToInt)
。例如,如果stringToInt
是'mystring'
,aValueError
将被引发。
To avoid ValueError
s, so long as you're not making a generator expression, use a try-except:
为了避免ValueError
s,只要您不创建生成器表达式,请使用 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 variable
to None
for other common errors: stringToInt='ZZTop'
, for example.
这具有绑定variable
到None
其他常见错误的令人愉快的副作用: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