83

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.

user1039163
  • 839
  • 1
  • 6
  • 3

6 Answers6

132

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.

Nathan Jones
  • 4,904
  • 9
  • 44
  • 70
  • 9
    +1 for being specific. It's worth noting that the `ValueError` `Exception` instance will contain more information, *viz.* "invalid literal for int() with base 10: 'abcd'". – johnsyweb Nov 10 '11 at 07:13
  • 6
    Just wanted to mention... if there's a chance the variable you are converting is `None`, then you'll want your except block to be `except (TypeError, ValueError):` – Jason Capriotti Mar 31 '21 at 18:46
27

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
gecco
  • 17,969
  • 11
  • 51
  • 68
  • 9
    -1 for catching almost every possible exception instead of just `ValueError`. You should only catch what you know how to deal with. – Ethan Furman Nov 10 '11 at 16:25
  • 13
    Catching more than you need is **very** bad practice. Adjust your answer and I'll happily change my vote. – Ethan Furman Nov 10 '11 at 20:34
  • 3
    +1 This is just an example, so showing the pattern to catch a ValueError and also other kinds of exception is very didactic. It's very useful for example to parse an argument and set a default value if invalid or not defined. – Luis Vazquez Nov 08 '19 at 22:52
  • I happen to work on a very large python code base that had thrown a ton of exceptions left and right. And at one point there was no other way to deal with it but catching all - you do not know what new exception a member of a different team working in a different country added last week 10 layers below your code. Coming from c++ I would say exceptions in python are way overused. – uuu777 Nov 24 '21 at 15:04
13

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'
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
3

In many cases, we want to get an integer value from the user. Users may insert non-integer values that should be warned and they should be prompted to try again. The following snippet can be used to get an integer value from the user and continue prompting the user to insert an integer until they put a valid one.

def get_integer_value():
  user_value = input("Enter an integer: ")
  try:
    return int(user_value)
  except ValueError:
    print(f"{user_value} is not a valid integer. Please try again.")
    return get_integer_value()


if __name__ == "__main__":
  print(f"You have inserted: {get_integer_value()}")
    

Output:

Enter an integer: asd
asd is not a valid integer. Please try again.
Enter an integer: 32
You have inserted: 32
arshovon
  • 13,270
  • 9
  • 51
  • 69
2

Unfortunately, the official documentation does not tell much about the exceptions that int() can raise; however, when you use int(), it can raise essentially two exception: TypeError, if the value is not a number or a string (or bytes, or bytearray), and ValueError if the value does not really map to a number.

You should manage both, with something like this:

try:
   int_value = int(value)
except (TypeError, ValueError):
    print('Not an integer')
rob
  • 36,896
  • 2
  • 55
  • 65
1

You can do :

try : 
   string_integer = int(string)
except ValueError  :
   print("This string doesn't contain an integer")
  • The syntax of your except statement is wrong - it will never catch anything. Multiple exceptions are caught using `except (type1, type2):` syntax. And there is no point combining a specific error with the general base class `Exception`. – Richard Whitehead Jul 10 '20 at 15:12