Convert string to number in Python

This basic example helps us explain how we can convert string to number in Python. If we are starting with Python we are going to find on many occasions that the type of data we are handling is a text string. If we read it from a database, if it is a value that we have recovered from a request to the server,…

And what we don’t want to get is the surprise that when manipulating it as a number we obtain unexpected results.

And it can happen to us if we have the following code:

n1 = '3'
n2 = '4'

print n1+n2

It shows us as a result a ’34’ instead of a 7.

So we will have to convert string to number in Python. And to do this we must use the int() method. This method will receive the string we want to convert as a variable.

In this way the code to be written must be:

n1 = '3'
n2 = '4'

print int(n1)+int(n2)

We will have already managed to manipulate the numbers correctly.

Lastly, we can indicate that if you do not know what the type of a variable is in Python, you can use the type() method.

print type(n1)

We already see how simple and useful it is to convert string to number in Python.

Leave a Comment