How to Turn a String Into an Int in Python

In Python programming, it may sometimes be necessary to convert data types, either to enable certain operations or to create a cleaner, more efficient code.

A common conversion in Python – and the subject of this tutorial – is converting a string into an integer.

Thankfully, Python makes it easy to convert a string data type into an integer (int) data type using the built-in int() function.

Basic String to Int Conversion

The first step of converting a string into an integer in Python involves the straightforward usage of the built-in int() function.

In this case, “123” is the string that you want to convert. After the conversion, the print() function is used to print out the converted integer.

The int() Function with a Base Parameter

In addition to the default usage, the int() function in Python also allows you to provide a second argument that acts as the base for conversion. This base parameter must be between 2 and 36, inclusive.

This allows for conversion from different base number systems, like binary in this case – the number 1010 in binary (base 2) is equal to the number 10 in decimal (base 10).

Handling Conversion Errors

When using the int() function, you must ensure that the string being converted is actually capable of being represented as an integer. If it isn’t, Python will raise a ValueError. You can handle this error using a try-except block:

Here, the conversion of “Hello World!” to an integer results in a ValueError which is then caught and handled gracefully by printing out an error message.

Full Code

Here is the full code for converting string to integer in Python:

Output:

123
10
Cannot convert the string into an integer

Conclusion

Taking advantage of Python’s built-in functions can make data type conversions quick and easy. While this tutorial specifically addressed turning a string into an integer, as you continue to explore Python, you’ll find that this is just one of many conversions you may have to perform. The more familiar you become with Python’s built-in functions, the more efficiently you’ll be able to write code to suit your needs.