Welcome, guest | Sign In | My Account | Store | Cart

This recipe shows how to convert numeric strings into integers, i.e. it emulates the Python int() function - partially. It does not handle negative numbers, floating point numbers, or numbers in other bases than decimal. It is only meant as a simple demo of the steps by which a string containing an integer value, is converted into an actual integer, in Python (and similarly, in other languages).

Python, 19 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
def str_to_int(s):
    ctr = i = 0
    for c in reversed(s):
        i += (ord(c) - 48) * (10 ** ctr)
        ctr += 1
    return i

print
for s in ('0', '1', '2', '3', '12', '123', '234', '456', '567'):
    i = str_to_int(s)
    print "s = {}, i = {} |".format(s, i),

print
print

for i in range(50):
    s = str(i)
    j = str_to_int(s)
    print "s = {}, j = {} |".format(s, j), 

This recipe is intended only to show the steps underlying the process of converting a numeric string (containing a non-negative decimal number only) to an integer. It does not handle numbers in other bases, or negative numbers, or floating point number strings. Adding support for negative numbers is simple, handling numbers in other bases is not as simple, but doable, along the same lines of the algorithm used in this recipe. Also, this recipe has not been tuned for the best performing code or shortest or clearest possible code, since the intention was only to use it to demonstrate the steps involved in converting a numeric string into an integer.

4 comments

Vasudev Ram (author) 8 years, 9 months ago  # | flag
hallsville3 8 years, 8 months ago  # | flag

I don't mean to diminish the work that you did in any way, but in Python the built in eval() function does the same thing. For instance, eval('1337') == 1337 Furthermore, eval('-1337') == -1337 The function takes Python code as a string and evaluates it as if it were entered in the interperator. Nice work anyways!

Vasudev Ram (author) 8 years, 8 months ago  # | flag

Thanks for your comment.

I have known about eval - almost from the time I first learned Python. The purpose of this recipe (and the blog post linked above) was to show to beginners, the basics of how numeric strings are converted to integers. That purpose could not be achieved with eval, since eval hides the process of how it is done - unless you look at eval's source code, and even then it is too generic and broader in scope than just converting strings to integers.

Also, eval has security risks.

Vasudev Ram (author) 8 years, 8 months ago  # | flag

Further:

was to show to beginners, the basics of how numeric strings are converted to integers.

To show the main principles, not every corner case.