Search code examples
pythoncastingintcalculus

Why is python returning a numbers from a string?


OK, this is completely confusing me to bits, I am printing a string and its returning numbers. I don't understand how it is returning numbers from a string.

Here is the code snippet.

string = "String"
print int(string[0:min(5,len(string))],36)

the output of that snippet is

48417935

My friend was telling me it has something to do with the computer generating numbers from strings, but I am just so confused.

Can someone please be kind enough and explain to why this is happening?


Solution

  • You are taking this slice

    >>> string[0:min(5,len(string))]
    'Strin'
    

    and converting it as a base36 number (similar to hexadecimal but using all 26 letters)

    >>> int('Strin', 36)
    48417935
    

    Another way to arrive at this figure is:

    >>> ["0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".index(x) for x in 'STRIN']
    [28, 29, 27, 18, 23]
    >>> 28*36**4 + 29*36**3 + 27*36**2 + 18*36**1 + 23*36**0
    48417935