It is important to be specific about what exception you're trying to catch when using a try/except block.
string = "abcd"
try:
string_int = int(string)
print(string_int)
except ValueError:
# Handle the exception
print('Please enter an integer')
Try/Excepts are powerful because if something can fail in a number of different ways, you can specify how you want the program to react in each fail case.
Answer from Nathan Jones on Stack OverflowConverting String to Int using try/except in Python - Stack Overflow
Safe casting in python - Stack Overflow
Add a default option to int() to use if conversion fails - Ideas - Discussions on Python.org
parsing - Python "safe" eval (string to bool/int/float/None/string) - Stack Overflow
It is important to be specific about what exception you're trying to catch when using a try/except block.
string = "abcd"
try:
string_int = int(string)
print(string_int)
except ValueError:
# Handle the exception
print('Please enter an integer')
Try/Excepts are powerful because if something can fail in a number of different ways, you can specify how you want the program to react in each fail case.
Here it is:
s = "123"
try:
i = int(s)
except ValueError as verr:
pass # do job to handle: s does not contain anything convertible to int
except Exception as ex:
pass # do job to handle: Exception occurred while converting to int
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
my_input = int(my_input)
There is no shorter way than using the int function (as you mention)
Maybe you were hoping for something like my_number = my_input.to_int. But it is not currently possible to do it natively. And funny enough, if you want to extract the integer part from a float-like string, you have to convert to float first, and then to int. Or else you get ValueError: invalid literal for int().
The robust way:
my_input = int(float(my_input))
For example:
>>> nb = "88.8"
>>> int(nb)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '88.8'
>>> int(float(nb))
88
If you want a one-liner like you've attempted, go with this:
variable = int(stringToInt) if stringToInt else None
This will assign variable to int(stringToInt) only if stringToInt is not empty AND is "numeric". If, for example stringToInt is 'mystring', a ValueError will be raised. If stringToInt is empty (''), it will assign variable to None.
To avoid ValueErrors, use a try-except:
try:
variable = int(stringToInt)
except ValueError:
variable = None
I think this is the clearest way:
variable = int(stringToInt) if stringToInt.isdigit() else None