This tutorial describes how to convert a Python string to int and vice versa.

Python Convert String to int

Use Python int() function to convert a string value to integer in Python. This function accepts two parameters, one is the string in quotes and the second is an optional base to represent the data. Use the following syntax to return the string value as an integer Open a Python shell to run tests below:

You can also check the type of value stored in a variable. Like, store a number as a string to a variable and verify that the type is “str”. Next, convert the Python string to int and again check the type of value. You will find that the type of value is int.

The input must contain numerical values (0-9), nothing else. For example, if the input value contains non-numeric values (like alphabets, symbols) will throw an error with invalid literal. See the example below:

Python Convert Integer to String

You can also convert a numeric value to a string value. Use the python str() function to convert an integer value to a string. The Python str() function syntax is: Run an example in the Python console.

Run a demonstration of type conversion by verifying the data type. Run the below commands in the Python shell one by one.

You can see that the first time the datatype is showing to “int”. After the type conversion with the Python str() function, the new datatype is showing to “str”.

Conclusion

The Python int() method is used to convert a string value to an integer value. This is useful to perform mathematical operations on a numeric value stored as a string. Suggested reading: Here are more useful examples of string conversions in the Python programming languages.

Convert String to Lowercase in Python Convert String to Uppercase in Python