In this tip of the day, we will show you how to convert a string to int in Python programming language using a practical example.
The Python programming language provides a handy function int() that you can use to convert a string value to an int numeric value. Here is how you can use this feature.
To use this feature you must have installed Python on your system. Windows users can follow these steps here.
Open a Python shell by running the following command in your terminal or cmd.
Now run the following code below:
# Pick a string representation of a number >>> s = '100' #Confirm the type of the variable >>> type(s) <class 'str'> #Convert String to Int >>> s = int(s) #Again confirm the type of the variable >>> type(s) <class 'int'> #This time the string has been converted to int.
If the string value above is not a string representation of an int (it must contain the digits 0-9 and nothing more) it will throw an error. Check out this example:
>>> s = '100f' >>> >>> s = int(s) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: '100f'
That’s it. You can use the int() function in Python on your system.