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

Improve your Python skills fast

The fastest way to learn programming is with lots of practice. Learn a programming concept, then write code to test your understanding and make it stick. Try our online interactive Python course today—it's free!

Learn more about the course

Want to get better at Python quickly? Try our interactive lessons today! Memberships are 100% FREE this week only!