python中bin()函数的用法,返回二进制值

bin()函数描述

python的内置的数据转换的函数bin(),接收一个int整形数值作为参数,返回一个以字符串形式表示的二进制值。在python当中,二进制字符串以“0b”。


bin()函数参数语法结构

该语法结构来源于python的部分源码:

def bin(number: Union[int, _SupportsIndex])

bin()函数返回值

python的源码当中有这么一句话,指明了bin()函数的返回值:Return the binary representation of an integer.即传入整型参数的二进制值。


bin()函数实例代码

>>> bin(1)
'0b1'
>>> bin(2)
'0b10'
>>> bin()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bin() takes exactly one argument (0 given)
>>> bin('1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer
>>> bin(b'2')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'bytes' object cannot be interpreted as an integer

代码解析

如上代码,从python抛出的三个TypeError,及相关的提示,可以看出,bin()函数确实需要一个参数、不接收字符串、字节串等整形数值之外的相关数据。其它的,大家可以自己多多尝试,比如传入一个float浮点型的数据试一试。



全栈后端 / python教程 :


























Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.