1. 程式人生 > >Python3內置函數——bin

Python3內置函數——bin

define with cin returns solid lpad 十六進制 pytho orm

先上英文文檔:

bin(x)

Convert an integer number to a binary string prefixed with “0b”. 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. Some examples:

>>>
>>> bin(3)
‘0b11‘
>>> bin(-10)
‘-0b1010‘

If prefix “0b” is desired or not, you can use either of the following ways.

>>>
>>> format(14, ‘#b‘), format(14, ‘b‘)
(‘0b1110‘, ‘1110‘)
>>> f{14:#b}, f{14:b}(‘0b1110‘, ‘1110‘)

See also format() for more information.

我們暫時只討論x為整數型數據時發生的情形。

整理出函數信息表:

函數原型

bin(x)

參數解釋

x

整數型,參數不可為空。

返回值

<class ‘str‘> 字符串類型,二進制整數。

函數說明

將一個整數轉化為一個二進制整數,並以字符串的類型返回。

容易理解,該函數接受且只接受一個整數,並以二進制的形式返回。

>>> bin(0)
0b0
>>> print(bin(-729))
-0b1011011001

需要註意的是,該函數的返回值是一個字符串,不應將返回值進行計算。

>>> type(bin(729))
<class str>
>>> bin(10) * 2
0b10100b1010

如果需要進行計算,需要使用int函數將字符串轉換成int型數據。

>>> int(bin(729), base = 2)  #base參數不可空,否則會報錯
729

當然了,參數不僅可以接受十進制整數,八進制、十六進制也是可以的,只要是int型數據就合法。

1 >>> bin(0b10010)
2 0b10010
3 >>> bin(0o12345)
4 0b1010011100101
5 >>> bin(0x2d9)
6 0b1011011001

Python3內置函數——bin