英文文件:
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__()##__index__() method that returns an integer.
說明:
1. 將一個整形數字轉換成二進位字串>>> b = bin(3) >>> b '0b11' >>> type(b) #获取b的类型 <class 'str'>
>>> class A: pass >>> a = A() >>> bin(a) Traceback (most recent call last): File "<pyshell#15>", line 1, in <module> bin(a) TypeError: 'A' object cannot be interpreted as an integer
>>> 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)
>>> class C: def __index__(self): return 3 >>> c = C() >>> bin(c) '0b11'
#
以上是Python內建bin函數詳細介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!