Python string to int conversion – How to Convert a Python String to int

Convert Python String to Int:

Python string to int conversion: To convert a string to integer in Python, use the int() function. This function takes two parameters: the initial string and the optional base to represent the data. In Python an strings can be converted into a integer using the built-in int() function. The int() function takes in any python data type and converts it into a integer.But use of the int() function is not the only way to do so. This type of conversion can also be done using thefloat() keyword, as a float value can be used to compute with integers.

Below is the list of possible ways to convert an integer to string in python:

1. Using int() function:



Using int() function


Using int() function output
As a side note, to convert to float, we can use float() in python:


use float() in python


use float() in python output
2. Using float() function:

We first convert to float, then convert float to integer. Obviously the above method is better (directly convert to integer).

Syntax: float(string)




Using float() function output

If you have a decimal integer represented as a string and you want to convert the Python string to an int, then you just follow the above method (pass the string to int()), which returns a decimal integer.But By default, int() assumes that the string argument represents a decimal integer. If, however, you pass a hexadecimal string to int(), then you’ll see a ValueError

For value error

The error message says that the string is not a valid decimal integer.

When you pass a string to int(), you can specify the number system that you’re using to represent the integer. The way to specify the number system is to use base:

Now, int() understands you are passing a hexadecimal string and expecting a decimal integer.


This article is all about how to convert python string to int.All methods are clearly explained here. Now I hope you’re comfortable with the ins and outs of converting a Python string to an int.