Converting String to Int using try/except in Python

PythonPython 3.x

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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

Solution 3 - Python

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'

Solution 4 - Python

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

Solution 5 - Python

You can do :

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1039163View Question on Stackoverflow
Solution 1 - PythonNathan JonesView Answer on Stackoverflow
Solution 2 - PythongeccoView Answer on Stackoverflow
Solution 3 - PythonjohnsywebView Answer on Stackoverflow
Solution 4 - PythonarshoView Answer on Stackoverflow
Solution 5 - Pythonsoufiane yesView Answer on Stackoverflow