Search code examples
pythonnumbersconvertersradix

Convert string to decimal (base 10) in Python


I've tried to create a simple method to convert a string into a base-10 integer (in Python):

def strToNum(strData, num=0 ,numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
    return ((len(strData)==0) and num) or (strToNum(strData[0:-1], num+numerals.index(strData[-1])**len(strData)))

It doesn't seem to work. When I tested out 'test' as the string it outputted: 729458. And when I used some online tools to convert, I got: 1372205.


Solution

  • You can simply use int here:

    >>> strs = 'test'
    >>> int(strs, 36)
    1372205
    

    Or define your own function:

    def func(strs):
        numerals = "0123456789abcdefghijklmnopqrstuvwxyz"
        return sum(numerals.index(x)*36**i for i, x in enumerate(strs[::-1]))
    ... 
    >>> func(strs)
    1372205