Python Principles

How to convert a string to int in Python

To convert a string to an integer, use the built-in int() function. The function takes a string as input and returns an integer as its output.

Example

Here's an example of using int():

>>> string = "123"
>>> int(string)
123

Why convert a string?

You need to convert a string to an int before you can use it to calculate things. In other words, changing the type of a variable can affect the behavior when using that variable.

As an example, consider the difference between the two uses of + in this example:

>>> "123" + "456"
'123456'
>>> int("123") + int("456")
579

Handling malformed strings

Some strings do not represent valid numbers. If you try to convert such a string, you will get an exception:

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

To handle such cases, use a try/except block:

try:
    number = int(some_variable)
except ValueError:
    print("some_variable did not contain a number!")

Handling floating-point numbers

Sometimes your number has a dot in it. In this case, you might want to use float() instead of int(); otherwise you will get an error:

>>> text = "123.456"
>>> int(text)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '123.456'
>>> float(text)
123.456

Custom base

If your string uses a different base, you can specify the base as a second argument to int(). For example:

>>> int("0x123", 16)
291

Want to get better at Python?

Try our practical beginner lessons, or test your skills with our challenges.

View Lessons Try Challenges