Search⌘ K

Integer to String

Explore how to convert an integer to its string representation in Python without using the built-in str function. Learn to use ord and chr functions to manipulate Unicode code points, handle positive and negative numbers, and build the final string step-by-step.

We'll cover the following...

In this lesson, we will solve the following problem:

You are given some integer as input, (i.e. … -3, -2, -1, 0, 1, 2, 3 …) and you have to convert the integer you are given to a string. Examples:

    Input: 123
    Output: "123"
    Input: -123
    Output: "-123"

Note that you cannot make use of the built-in str function:

Python 3.5
print(str(123))
print(type(str(123)))

Before diving into the implementation of the solution, we need to get familiar with the following functions:

  1. ord()
  2. chr()

You might be able to recall ord() from one of the previous lessons. ord() returns an integer which represents the Unicode code point of the Unicode character passed into the function. On the other hand, chr() is the exact opposite of ord(). chr() returns a character from an integer that represents the Unicode code point of that character.

Python 3.5
## Prints 48 which is the Unicode code point of the character '0'
print(ord('0'))
## Prints the character '0' as 48 is Unicode code point of the character '0'
print(chr(ord('0')))
## Prints 49
print(ord('0')+ 1)
## Prints 49 which is Unicode code point of the character '1'
print(ord('1'))
## Prints the character '2' as 50 is Unicode code point of the character '2'
## ord('0') + 2 = 48 + 2 = 50
print(chr(ord('0')+ 2))
## Prints the character '3' as 51 is Unicode code point of the character '3'
## ord('0') + 3 = 48 + 2 = 51
print(chr(ord('0')+ 3))

From the above coding example, you can observe the following pattern:

ord('0') = 48
ord('1') = ord('0') + 1 = 48 + 1 = 49 
ord('2') = ord('0') + 2 = 48 + 2 = 50 

chr(ord('0')) = chr(48) = '0' 
chr(ord('0') + 1) = chr(48 + 1) =
...