Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe casting in python

Tags:

python

casting

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="fifteen";
var x=word as int32// here I get null

Has python something similar to this?

like image 248
user278618 Avatar asked Jun 13 '11 11:06

user278618


People also ask

Does Python allow casting?

Python allows you to cast various data types into one another. This also allows you to specify a data type to a variable. This is called Python Casting.

What are all the Type Casting possible in Python?

Explicit Type CastingInt() : Int() function take float or string as an argument and return int type object. float() : float() function take int or string as an argument and return float type object. str() : str() function take float or int as an argument and return string type object.

What is meant by casting in Python?

Explicit Type Casting This type casting in Python is mainly performed on the following data types: int(): takes a float or string object as an argument and returns an integer-type object. float(): takes int or string object as an argument and returns a float-type object.

How do you cast a float in Python?

Integer and Float Conversions To convert the integer to float, use the float() function in Python. Similarly, if you want to convert a float to an integer, you can use the int() function.


4 Answers

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
like image 54
Artsiom Rudzenka Avatar answered Sep 29 '22 10:09

Artsiom Rudzenka


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
like image 25
drogon2 Avatar answered Sep 29 '22 11:09

drogon2


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
    # ...       
like image 26
Zaur Nasibov Avatar answered Sep 29 '22 09:09

Zaur Nasibov


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
like image 20
unbeli Avatar answered Sep 29 '22 10:09

unbeli