Skip to main content
Taught by Tech Leads

Master pipelines, cloud & AI to become an operational Data Engineer.

DataScientist.fr
Image de Convert Python integers to strings - Interactive Tutorial
Python

Convert Python integers to strings - Interactive Tutorial

Photo de Romain DE LA SOUCHÈRE

Tech Lead, CTO AXI Technologies

Published on 31 décembre 2024 · 4 min of reading

In Python, manipulating integers may seem straightforward, but it conceals fascinating nuances. Whether you're a novice or a seasoned programmer, understanding how integers are represented and converted between different data types is crucial. Let's dive into the mechanisms of storing and converting integers using the str and int types, and discover how to juggle with number systems to optimize your Python code. Get ready to enrich your skills and explore the subtleties of integers in Python in a fun and informative way!

Representation of integers in Python

An integer can be stored using different types. Two possible Python data types for representing an integer are:
  1. str
  2. int
For example, you can represent an integer using a string literal:
python
Here, Python understands that you want to store the integer 110 as a string. You can do the same with the integer data type:
python
It is important to consider what you specifically mean by "110" and 110 in the examples above. As a human who has used the decimal number system your whole life, it may be obvious that you mean the number one hundred ten. However, there are several other number systems, such as binary and hexadecimal, that use different bases to represent an integer.
For example, you can represent the number one hundred ten in binary and hexadecimal as 1101110 and 6e respectively.
You can also represent your integers with other number systems in Python using the str and int data types:
python
Note that binary and hexadecimal use prefixes to identify the number system. All integer prefixes are in the form 0?, where you replace ? with a character referring to the number system:
  • b: binary (base 2)
  • o: octal (base 8)
  • d: decimal (base 10)
  • x: hexadecimal (base 16)
Technical detail: The prefix is not required in an integer or string representation when it can be inferred.
int assumes that the integer literal is decimal:
python
The string representation of an integer is more flexible since a string contains arbitrary textual data:
python
Each of these strings represents the same integer.
Now that you have some foundational knowledge on how to represent integers using str and int, you will learn how to convert a Python string to int.

Converting a string to int

If you have a decimal integer represented as a string and you want to convert that Python string to int, you can simply pass the string to int(), which returns a decimal integer:
python
By default, int() assumes that the string argument represents a decimal integer. However, if you pass a hexadecimal string to int(), you will see a ValueError:
python
The error message indicates that the string is not a valid decimal integer.
Note:
It is important to recognize the difference between two types of failed results when passing a string to int():
  1. Syntax error: A ValueError will occur when int() does not know how to parse the string using the provided base (10 by default).
  2. Logical error: int() knows how to parse the string, but not in the way you expected.
Here is an example of a logical error:
python
In this example, you wanted the result to be 210, which is the decimal representation of the binary string. Unfortunately, because you did not specify this behavior, int() assumes that the string is a decimal integer.
A good precaution for this behavior is to always define your string representations using explicit bases:
python
Here, you get a ValueError because int() does not know how to parse the binary string as a decimal integer.
When you pass a string to int(), you can specify the number system you are using to represent the integer. The way to specify the number system is by using the base parameter:
python
Now, int() understands that you are passing a hexadecimal string and you expect a decimal integer.
Technical detail: The argument you pass to base is not limited to 2, 8, 10, and 16:
python
Great! Now that you are comfortable with the ins and outs of converting a Python string to int, you will learn to do the reverse operation.

Converting an int to a string

In Python, you can convert an int to a string using str():
python
By default, str() works like int() in that it results in a decimal representation:
python
In this example, str() is smart enough to interpret the binary literal and convert it to a decimal string.
If you want a string to represent an integer in another number system, you use a formatted string, like an f-string (in Python 3.6+), and an option that specifies the base:
python
str is a flexible way to represent an integer in various different number systems.

Conclusion

Congratulations! You have learned so much about integers and how to represent and convert them between string and int data types in Python.
In this tutorial, you learned:
  • How to use str and int to store integers
  • How to specify an explicit number system for integer representation
  • How to convert a Python string to int
  • How to convert a Python int to a string
Now that you know so much about str and int, you can learn more about representing numerical types using float(), hex(), oct(), and bin()!

Want to go further?

This topic is part of our Become a Data Analyst course. Browse the full programme, or get it by email.

Share with

Photo de Romain DE LA SOUCHÈRE

Romain DE LA SOUCHÈRE

Tech Lead, CTO AXI Technologies

Expert Data Engineering et Cloud, Romain affiche plus de 11 ans d'expérience, dont plusieurs années comme Lead Developer sur des solutions Smart Building haute performance. Il y a conçu et mis en production des moteurs de traitement capables d'absorber des centaines de milliers de données de capteurs par minute, ainsi que des bases clusterisées gérant plus de 10 millions de données dynamiques. Certifié Microsoft Azure DevOps Engineer Expert, il maîtrise aussi bien le développement back-end (Python, C#) que le DevOps (Docker, Kubernetes, Terraform) et les agents LLM. Formateur en Python, cloud, DevOps et IA générative appliquée, il forme avec une obsession : Amener chaque apprenant à concevoir et déployer des architectures réellement scalables en production.

» Learn More

Associated trainings

All our trainings
Image de la formation Become a Data Analyst
Become a Data Analyst
6 months
Intermediate
Guarantee