Home > Backend Development > Python Tutorial > Detailed introduction to Python's built-in bin function

Detailed introduction to Python's built-in bin function

高洛峰
Release: 2017-03-21 11:33:40
Original
2733 people have browsed it

English documentation:

bin(x)

Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.

Instructions:

1. Convert an integer number into a binary string

>>> b = bin(3) 
>>> b
'0b11'
>>> type(b) #获取b的类型
<class &#39;str&#39;>
Copy after login

2. If the parameter x is not an integer, then x must define an __index__() method, and the method return value must be an integer.

2.1 If the object is not an integer, an error will be reported

>>> class A:
    pass

>>> a = A()
>>> bin(a) 
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    bin(a)
TypeError: &#39;A&#39; object cannot be interpreted as an integer
Copy after login

2.2 If the object defines the __index__ method, but the return value is not an integer, an error will be reported

>>> class B:
    def __index__(self):
        return "3"

>>> b = B()
>>> bin(b)
Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>
    bin(b)
TypeError: __index__ returned non-int (type str)
Copy after login

2.3 The object defines _ _index__ method, and the return value is an integer, convert the __index__ method return value into a binary string

>>> class C:
    def __index__(self):
        return 3

>>> c = C()
>>> bin(c)
&#39;0b11&#39;
Copy after login

The above is the detailed content of Detailed introduction to Python's built-in bin function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template