Safe casting in python

后端 未结 5 1239
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
    
    0 讨论(0)
  • 2020-12-31 04:04

    There is something similar:

    >>> word="15"
    >>> x=int(word)
    >>> x
    15
    
    
    >>> word="fifteen"
    >>> x=int(word)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: invalid literal for int() with base 10: 'fifteen'
    
    
    >>> try: 
    ...     x=int(word)
    ... except ValueError:
    ...     x=None
    ... 
    >>> x is None
    True
    
    0 讨论(0)
  • 2020-12-31 04:06

    I do realize that this is an old post, but this might be helpful to some one.

    x = int(word) if word.isdigit() else None
    
    0 讨论(0)
  • 2020-12-31 04:06

    I believe, you've heard about "pythonic" way to do things. So, safe casting would actually rely on "Ask forgiveness, not permission" rule.

    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
        # ...       
    
    0 讨论(0)
  • 2020-12-31 04:11

    Casting has sense only for a variable (= chunk of memory whose content can change)

    There are no variables whose content can change, in Python. There are only objects, that aren't contained in something: they have per se existence. Then, the type of an object can't change, AFAIK.

    Then, casting has no sense in Python. That's my believing and opinion. Correct me if I am wrong, please.

    .

    As casting has no sense in Python, there is no sense to try to answer to this question.

    The question reveals some miscomprehension of the fundamentals of Python and you will gain more profit obtaining answers after having explained what led you thinking that you need to cast something

    0 讨论(0)
提交回复
热议问题