{"id":9465,"date":"2021-01-18T12:19:12","date_gmt":"2021-01-18T17:19:12","guid":{"rendered":"http:\/\/local.brightwhiz\/?p=9465"},"modified":"2021-12-04T05:43:26","modified_gmt":"2021-12-04T05:43:26","slug":"convert-string-int-python-examples","status":"publish","type":"post","link":"http:\/\/local.brightwhiz\/convert-string-int-python-examples\/","title":{"rendered":"How to Convert a String to Int in Python With Examples"},"content":{"rendered":"\n

At this tip of the day, we will show you how to convert a string to int in the Python programming language using a practical example.<\/p>\n\n\n\n

The Python programming language provides a handy function int()<\/strong> that you can use to convert a string value to an int numeric value. Here is how you can use this feature.<\/p>\n\n\n\n

To use this feature you must have installed Python<\/a> on your system. Windows users can follow these steps here.<\/p>\n\n\n\n

Open a Python shell by running the following command in your terminal or cmd.<\/p>\n\n\n\n

$ python<\/code><\/p>\n\n\n\n

Now run the following code below:<\/p>\n\n\n\n

# Pick a string representation of a number\n>>> s = '100'\n \n#Confirm the type of the variable\n>>> type(s)\n<class 'str'>\n \n#Convert String to Int\n>>> s = int(s)\n \n#Again confirm the type of the variable\n>>> type(s)\n<class 'int'>\n\n#This time the string has been converted to int.<\/code><\/pre>\n\n\n\n

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:<\/p>\n\n\n\n

>>> s = '100f'\n>>>\n>>> s = int(s)\nTraceback (most recent call last):\n  File "<stdin>", line 1, in <module>\nValueError: invalid literal for int() with base 10: '100f'<\/code><\/pre>\n\n\n\n

That’s it. You can use the int()<\/strong> function in Python on your system.<\/p>\n\n\n\n

Related:<\/strong><\/p>\n\n\n\n