A string is a sequence of characters, numbers, and special characters together. An integer is a set of numbers that includes zero, negative and positive numbers without any decimal or fractional parts. Datatype is a classification of data, which tells the compiler or interpreter, how the programmer intends to use the data. Similar to other programming languages Python also supports datatype conversions.
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
int("number", base=base)
Open a Python shell to run tests below:
1 2 | >>> print(int("100")) 100 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | # Assign a number as string to variable >>> s = "100" # Check the datatype >>> type(s) <type 'str'> # Python Convert string to int >>> s = int(s) # Again check the datatype >>> type(s) <type '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:
1 2 3 4 5 6 | >>> s = '10e' >>> >>> s = int(s) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: '10v0' |
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:
str(number)
Run an example in the Python console.
1 2 | >>> print(str(100)) 100 |
Run a demonstration of type conversion by verifying the data type. Run the below commands in the Python shell one by one.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | # Assign a number as inter to variable >>> s = 100 # Check the datatype >>> type(s) <class 'int'> # Convert integer to string >>> s = str(s) # Again check the datatype >>> type(s) <class 'str'> |
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.