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?
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.
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.
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.
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.
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
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
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
# ...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With