Safe casting in python

后端 未结 5 1238
Happy的楠姐
Happy的楠姐 2020-12-31 03:36

How to do safe cast in python

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=\"fifte         


        
5条回答
  •  轮回少年
    2020-12-31 03:59

    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
    

提交回复
热议问题