"The Daily Python function" topic has been sharing Python's built-in functions last week, all in alphabetical order, but the 4 functions explained last week are less commonly used, and today I am very happy, oh, because today I want to share with you a very common function: Bin () function
Bin (x)
English Note: Convert An integer number to a binary string. The result is a valid Python expression. If X was not a Python int object, it had to define an __index__ () method, which returns an integer.
New in version 2.6.
英文说明: Converts an integer x to a binary string, and if x is not of type int in Python, x must contain the method __index__ () and the return value is integer;
Parameter x: An integer or a type containing the __index__ () method that returns a value of integer;
Version: The bin function is a new function in python2.6, and you should pay attention to the version problem when using.
Example Explanation:
#整数的情况 >>> Bin (521) #这里的显示结果形式与我们平时习惯有些差别, mostly 0b ahead, which means binary. ' 0b1000001001 ' #非整型的情况, must contain the __index__ () method to cut the return value to integer type >>> class MyType: ... def __index__ (self): ... return 3 5 >>> myvar = MyType () >>> bin (myvar) ' 0b1000001001 '
PS: Changing the function is very simple, but note the version, and the parameter type.