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:
Before diving into the implementation of the solution, we need to get familiar with the following functions:
ord()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.
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) = ...