[python] Converting String to Int using try/except in Python

So I'm pretty stumped on how to convert a string into an int using the try/except function. Does anyone know a simple function on how to do this? I feel like I'm still a little hazy on string and ints. I'm pretty confident that ints are related to numbers. Strings...not so much.

This question is related to python python-3.x

The answer is


You can do :

try : 
   string_integer = int(string)
except ValueError  :
   print("This string doesn't contain an integer")

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

Firstly, try / except are not functions, but statements.

To convert a string (or any other type that can be converted) to an integer in Python, simply call the int() built-in function. int() will raise a ValueError if it fails and you should catch this specifically:

In Python 2.x:

>>> for value in '12345', 67890, 3.14, 42L, 0b010101, 0xFE, 'Not convertible':
...     try:
...         print '%s as an int is %d' % (str(value), int(value))
...     except ValueError as ex:
...         print '"%s" cannot be converted to an int: %s' % (value, ex)
...
12345 as an int is 12345
67890 as an int is 67890
3.14 as an int is 3
42 as an int is 42
21 as an int is 21
254 as an int is 254
"Not convertible" cannot be converted to an int: invalid literal for int() with base 10: 'Not convertible'

In Python 3.x

the syntax has changed slightly:

>>> for value in '12345', 67890, 3.14, 42, 0b010101, 0xFE, 'Not convertible':
...     try:
...         print('%s as an int is %d' % (str(value), int(value)))
...     except ValueError as ex:
...         print('"%s" cannot be converted to an int: %s' % (value, ex))
...
12345 as an int is 12345
67890 as an int is 67890
3.14 as an int is 3
42 as an int is 42
21 as an int is 21
254 as an int is 254
"Not convertible" cannot be converted to an int: invalid literal for int() with base 10: 'Not convertible'

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.