Convert int to string python without str | Example code

Use the chr function to convert int to string without str() function in Python.

Convert int to string python without str() function

Simple example code keeps dividing a given int value by 10 and prepending the remainder to the output string. Use the ordinal number of '0' plus the remainder to obtain the ordinal number of the remainder, and then convert it to string using the chr function.

def int_to_string(i):
    string = ''
    while True:
        i, remainder = divmod(i, 10)
        string = chr(ord('0') + remainder) + string
        if i == 0:
            break
    return string


res = int_to_string(10)
print(type(res), res)

Output:

Convert int to string python without str

Source: stackoverflow.com

Do comment if you have any doubts and suggestions on this Python int to string code.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.