How to Convert Strings into Integers in Python

How to Convert Strings into Integers in Python

In this tutorial, we’ll show you how to convert a Python string to an integer using the `int()` function

All data types in Python, including integers and strings, are objects. Often when writing Python code, you will need to convert one data type to another. For example, to perform a math operation on a number represented as a string, it needs to be converted into an integer.

In this tutorial, we’ll show you how to convert a Python string to an integer.

Python int() Function

The built-in int() function returns a decimal integer object from a given number or string. It takes the following form:

int(x, base=10)

The `function accepts two arguments:

  • x - String or number to be converted to an integer.
  • base - It represents the numeral system of the first argument. Its value can be 0 and 2–36. If no base is given, the default is 10 (decimal integer).

Usually, integers are expressed in hexadecimal (base 16), decimal (base 10), octal (base 8), or binary (base 2) notation.

If the given argument cannot be represented as an integer, the function will throw a ValueError exception.

Converting a Python String into Integer

In Python, a ‘string’ is a list of characters which is declared using single ('), double ("), or triple quotes (""").

If a variable that contains only numbers is declared using quotes, its data type is set to String. Consider the following example:

days = "23"
type(days)

The type() function shows us that days is a String object.


Let's try to do a math operation on the variable:

print(days+5)

Python will throw a TypeError exception error because we cannot perform an addition calculation with string and integer:

Traceback (most recent call last):
  File "", line 1, in 
TypeError: cannot concatenate 'str' and 'int' objects

To convert a string representation of a decimal integer into int, pass the string to the int() function, which returns a decimal integer:

days = "23"
days_int = int(days)
type(days_int)

If you now try to do the math, the sum operation will be performed successfully:

print(days_int+5)
28

If the number includes commas, marking off thousands, millions, etc., you need to remove the commas before passing the number to the int() function:

total = "1,000,000"
int(total.replace(",", ""))
1000000

When converting strings that represent integers in different number systems, make sure you use the correct base.

For example, in the hexadecimal system, the number 54732 is represented as D5CF. To convert it to a decimal integer you need to use base 16:

int("D5CF", 16)
54735

If you pass the D5CF string to the int() function without setting a base, it will throw a ValueError exception:

int("D5CF")
Traceback (most recent call last):
  File "", line 1, in 
ValueError: invalid literal for int() with base 10: 'D5CF'

Conclusion

In Python, you can convert a string to an integer using the int() function. If you have any questions or feedback, feel free to leave a comment.

Thank you !

python

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Basic Data Types in Python | Python Web Development For Beginners

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

How To Compare Tesla and Ford Company By Using Magic Methods in Python

Magic Methods are the special methods which gives us the ability to access built in syntactical features such as ‘<’, ‘>’, ‘==’, ‘+’ etc.. You must have worked with such methods without knowing them to be as magic methods. Magic methods can be identified with their names which start with __ and ends with __ like __init__, __call__, __str__ etc. These methods are also called Dunder Methods, because of their name starting and ending with Double Underscore (Dunder).

Python Programming: A Beginner’s Guide

Python is an interpreted, high-level, powerful general-purpose programming language. You may ask, Python’s a snake right? and Why is this programming language named after it?

Hire Python Developers

Are you looking for experienced, reliable, and qualified Python developers? If yes, you have reached the right place. At **[HourlyDeveloper.io](https://hourlydeveloper.io/ "HourlyDeveloper.io")**, our full-stack Python development services...

Python any: How to Check If Element is Iterable or Not

Python any() function returns True if any element of an iterable is True otherwise any() function returns False. The syntax is any().