Convert string to int in Python

How Do You Convert a String to an Integer and Vice Versa in Python?

Do you want to learn how to convert a string to an int in Python? You are in the right place.

This tutorial will clearly show you how to do it.

The Python int() built-in function converts a string to an integer. This is required when you want to execute mathematical operations that would fail on a variable of type string. Python also provides the str() built-in function that performs the opposite data type conversion from int to string.

We will start by looking at how data type conversion works using int() and str(). Then we will analyse a practical example that requires the conversion of a variable from string to integer.

Here we go!

How Do You Write an Integer in Python?

When we talk about integers we refer to decimal whole numbers that are either positive or negative.

Examples of integers are -1, -3, 0 5, 136.

In Python you can represent integer numbers using two data types: int and string.

Int representation

>>> number = 225
>>> type(number)
<class 'int'>

String representation

>>> number = "225"
>>> type(number)
<class 'str'>

In both cases the output of the type built-in function shows that the first variable is an int and the second variable is a string (str).

Check this tutorial if you want to learn what class means in Python.

Now we will learn how to convert a string to an integer and vice versa. The process of converting a Python data type to a different data type is also known as type casting.

Converting a String to an Int in Python

Let’s dig a little deeper now…

To convert a string to an int you can use the Python int() built-in function.

>>> number = "225"
>>> int(number)
225

Confirm that the data type returned is an integer:

>>> type(int(number))
<class 'int'>

That was easy!

And here is what happens if we try to convert into an integer a string that doesn’t represent an int.

>>> number = "not-a-number-225"
>>> type(int(number))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'not-a-number-225'

The Python interpreter raises a ValueError exception because the value we have passed to the int() function is not a valid base10 number.

Converting an Int to a String in Python

Now, let me show you how to convert an int into a string.

To convert an int to a string you can use the Python str() built-in function.

>>> number = 225
>>> str(number)
'225'

Confirm that the data type returned is a string:

>>> type(str(number))
<class 'str'>

It worked!

And this is what we get back if we try to convert into a string an integer that is not in decimal format.

For example, let’s try to convert a binary number into a string.

To write a binary number in Python you have to prefix it with 0b.

>>> number = 0b010
>>> str(number)
'2'
>>> number = 0b110
>>> str(number)
'6'
>>> number = 0b100
>>> str(number)
'4'

That’s great, the str() function is smart enough to convert binary numbers into strings in decimal format.

When Do You Need to Convert a String to an Integer in Python?

You have learned how to move from strings to integers and vice versa.

But, why would you do it in your program?

Let’s create, for example, a program that takes a number as input and returns the square of that number.

To read the number from user input we will use the Python input() function.

Note: in this tutorial we are using Python 3.

number = input("Insert a number: ")
print("The number is: ", number)
print("The type of the number is: ", type(number))

[output]
Insert a number: 4
The number is:  4
The type of the number is:  <class 'str'>

Interesting…

This code shows that the input() function returns a string even if we have provided a number to it.

The Python input() function, in Python 3, receives an input, converts it into a string and returns the string.

Ok, now let’s see why converting this string to an int is important.

After reading the number from the user try to calculate the square of that number using the Python exponent operator.

number = input("Insert a number: ")
square = number**2

When you execute this code you get back the following TypeError exception.

Insert a number: 4
The number is:  4
The type of the number is:  <class 'str'>
Traceback (most recent call last):
  File "convert_string_to_int.py", line 4, in <module>
    square = number**2
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

That’s because we are trying to calculate the square of a string data type instead of an int.

That’s why we have to convert the value returned by the input() function to an int first.

Here is how we do it…

number = int(input("Insert a number: "))
print("The number is: ", number)
print("The type of the number is: ", type(number))
square = number**2
print("The square of {} is {}".format(number, square))

We have:

  • Used the int() built-in function to convert the output of the input() function to an integer.
  • Then we have calculated the value of the square variable using the exponent operator.
  • Finally we have used the string format() method to print a message that contains the value of the square variable.
Insert a number: 4
The number is:  4
The type of the number is:  <class 'int'>
The square of 4 is 16

Does it make sense?

How Do You Convert an Hex Number to Int in Python?

Before completing this tutorial I want to show you something else…

A way to convert a string that represents an hex number to an int.

To write an hex number in Python you have to prefix it with 0x.

Let’s see what happens when we use the int() function to convert this hex string to an int.

number = '0xba9'
int(number)

[output]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '0xba9'

The Python interpreter raises a ValueError exception because it assumes that the string we are trying to convert to int represents a decimal number.

To tell the int() function that the string represents an hexadecimal number we have to pass a second argument to the int() function: the base. In this case its value will be 16.

>>> int(number, 16)
2985

As you can see the string has been converted correctly to its decimal value.

Conclusion

And now let’s recap what we have covered in this Python tutorial:

  • An integer can be represented in Python using the int or string data types.
  • Converting a string to an int using the int() built-in function.
  • Converting an int to a string using the str() built-in function.
  • Using the conversion from string to int in a real example.
  • Converting an hex string to int.

Now you have everything you need to move between the int and string data types and to convert user input to the correct type if required.

So, give it a go and email me at hello@codefather.tech if you have any questions.

Leave a Reply

Your email address will not be published.

How to Import a Python Function fro... x
How to Import a Python Function from Another File