Safe casting in python

后端 未结 5 1217
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 04:04

    There is something similar:

    >>> word="15"
    >>> x=int(word)
    >>> x
    15
    
    
    >>> word="fifteen"
    >>> x=int(word)
    Traceback (most recent call last):
      File "", line 1, in 
    ValueError: invalid literal for int() with base 10: 'fifteen'
    
    
    >>> try: 
    ...     x=int(word)
    ... except ValueError:
    ...     x=None
    ... 
    >>> x is None
    True
    

提交回复
热议问题