You should always try whatever confuses you in python shell piece by piece, that way you can understand what is happening. Use a better shell like ipython
and be liberal to use its ?
to see what's happening in the background. Python is kind of a "self documenting" language.
Let's go through your code piece by piece :
print int(string[0:min(5,len(string))],36)
Ok let's start with min(5,len(string))
In [2]: string = "String"
In [3]: min(5,len(string))
Out[3]: 5
In [4]: min?
Docstring:
min(iterable[, key=func]) -> value
min(a, b, c, ...[, key=func]) -> value
With a single iterable argument, return its smallest item.
With two or more arguments, return the smallest argument.
Type: builtin_function_or_method
Pretty self explanatory.
Well let's go one step ahead :
string[0:min(5,len(string))]
We have already got a value out of min()
call , so this boils down do :
string[0:5]
As we already from the python
's way of list slicing, it will return the 5 elements of the string starting from string[0]
and ending with string[4]
.
So in our given string's case it will return :
In [5]: string[0:min(5,len(string))]
Out[5]: 'Strin'
now what does int('Strin',36)
means?
Let's go back to the shell :
In [6]: int??
Docstring:
int(x=0) -> int or long
int(x, base=10) -> int or long
Convert a number or string to an integer, or return 0 if no arguments
are given. If x is floating point, the conversion truncates towards zero.
If x is outside the integer range, the function returns a long instead.
So it's converting it to number in a 36 based number system. Lets see the default invocation for one last time...
In [7]: int('Strin')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-7-a13c6c79aa49> in <module>()
----> 1 int('Strin')
ValueError: invalid literal for int() with base 10: 'Strin'
Well that's expected, as base 10 number system doesn't have symbols S
or T
etc. Base 16 has extra symbols A
to F
. so it means base 36 system would have 36-10=26
symbols. That means it will have all of the english alphabet as it's symbol table. That's why it will not raise exception and will be able to convert any string literal to a number representation.