verify if a string can be converted in int in python

To verify if a string can be converted to an integer in Python, you can use a try-except block to catch the ValueError that would be raised if the string could not be converted to int.

Here's an example code block:

main.py
string_num = "123"
try:
    integer_num = int(string_num)
    print("String is convertible to integer")
except ValueError:
    print("String is not convertible to integer")
173 chars
7 lines

In this code, the string "123" is attempted to be converted to an integer using the int() function. If the conversion is successful, the variable integer_num will hold the integer value of 123, and the message "String is convertible to integer" will be printed. If the conversion fails, a ValueError will be raised and the message "String is not convertible to integer" will be printed.

gistlibby LogSnag