in python how to convert string to int ?

Published on Aug. 22, 2023, 12:15 p.m.

To convert a string to an integer in Python, you can use the built-in int() function.

Here is an example:

my_string = "123"
my_int = int(my_string)
print(my_int)

This will output 123, which is the integer representation of the string “123”.

If the string contains non-numeric characters or is empty, the int() function will raise a ValueError exception. To avoid this, you can use a try-except block to handle the exception.

Here is an example with error handling:

my_string = "abc"
try:
    my_int = int(my_string)
except ValueError:
    print("Could not convert to int")
else:
    print(my_int)

This will output “Could not convert to int”, since “abc” cannot be converted to an integer.

Tags:

related content