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
def String(List): return List.__str__(). This is a bit of a hack, but it doesn’t use thestrfunction, does it? ;)