用python安全转换 [英] Safe casting in python

查看:57
本文介绍了用python安全转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在python中安全地投射

How to do safe cast in python

在c#中,我可以通过关键字来安全地投射,例如:

In c# I can safe cast by keyword as, e.g.:

string word="15";
var x=word as int32// here I get 15

string word="fifteen";
var x=word as int32// here I get null

具有类似于python的东西

Has python something similar to this?

推荐答案

不认为,但是您可以实现自己的:

Think not, but you may implement your own:

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

这篇关于用python安全转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆