Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an integer into string without using in-built function?

I wanna ask how to convert an integer into string without using in-built function.

This is the original question:

Write a function string(ls) that returns a string representation of the list ls.

Note: do not use the built-in str() method for this task. We are attempting to emulate its behavior.

s = string(['a','b','c'])   # '['a','b','c']'

s = string([1,2,3])         # '[1, 2, 3]'

s = string([True])          # '[True]'

s = string([])              # '[]'

Restrictions: Don't just return str(ls)! Don't use the str.join method, don't use slicing.

Here is my code:

def string(ls):
    if len(ls)==0:
        mess="'[]'"
        return mess
    elif isinstance(ls[0],str):
        i=0
        mess="'["
        while True:
            if i==len(ls)-1:
                elem="'"+ls[i]+"'"
                mess=mess+elem
                break
            else:
                elem="'"+ls[i]+"', "
                mess=mess+elem
            i=i+1
        mess=mess+"]'"
        return mess
    else:
        i=0
        mess="'["
        while True:
            if i==len(ls)-1:
                elem=str(ls[i])+"]'"
                mess=mess+elem
                break
            else:
                elem=str(ls[i])+', '
                mess=mess+elem
            i=i+1
        return mess
like image 328
An Yan Avatar asked Mar 30 '26 16:03

An Yan


1 Answers

You can keep dividing a given integer 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

so that:

print(int_to_string(0))
print(int_to_string(5))
print(int_to_string(65))
print(int_to_string(923))

would output:

0
5
65
923
like image 162
blhsing Avatar answered Apr 02 '26 13:04

blhsing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!