我在使用python进行转换时遇到问题.
在c#中,我可以通过关键字安全地投射,例如:
string word="15";
var x=word as int32// here I get 15
string word="fifteen";
var x=word as int32// here I get null
Run Code Online (Sandbox Code Playgroud)
python(3.2)有类似的东西吗?
Art*_*nka 50
不要想,但你可以实现自己的:
def safe_cast(val, to_type, default=None):
try:
return to_type(val)
except (ValueError, TypeError):
return default
safe_cast('tst', int) # will return None
safe_cast('tst', int, 0) # will return 0
Run Code Online (Sandbox Code Playgroud)
小智 23
我确实意识到这是一篇旧帖子,但这可能对某些人有所帮助。
x = int(word) if word.isdigit() else None
Run Code Online (Sandbox Code Playgroud)
我相信,您已经听说过“ pythonic ”的处理方式。因此,安全投放实际上将取决于“请求宽恕,而不是允许”规则。
s = 'abc'
try:
val = float(s) # or int
# here goes the code that relies on val
except ValueError:
# here goes the code that handles failed parsing
# ...
Run Code Online (Sandbox Code Playgroud)