HowTo: Python Convert a String Into Integer

In Python, you can convert a string to an integer using the int() function. Here is an example:

string_num = "123"
int_num = int(string_num)
print(int_num)

Output:

123

You can also use the float() function to convert a string to a floating-point number.

string_num = "12.3"
float_num = float(string_num)
print(float_num)

Output:

12.3

If the string is not a valid number, the int() and float() functions will raise a ValueError exception. To handle this case, you can use the tryexcept block to catch the exception and handle it accordingly.

string_num = "abc"
try:
int_num = int(string_num)
print(int_num)
except ValueError:
print("The string is not a valid number.")

Output:

The string is not a valid number.

You can also use str.isdigit() to check if the string is a number or not before converting it to integer.

string_num = "123"
if string_num.isdigit():
int_num = int(string_num)
print(int_num)
else:
print("The string is not a valid number.")

Output:

123

It’s important to be aware that the int() and float() functions can also take an additional radix parameter that allows you to specify the base of the number. For example, int("1010", 2) will convert the string “1010” from binary to decimal.

Leave a Comment