python 在线

931Python Number(数字)

Python 如何将整数转化成二进制字符串

1、你可以自己写函数采用 %2 的方式来算。

>>> binary = lambda n: '' if n==0 else binary(n/2) + str(n%2)
>>> binary(5)
'101'
>>> 

2、采用 python 自带了方法 bin 函数,比如 bin(12345) 回返回字符串 '0b11000000111001', 这个时候在把0b去掉即可:

>>> bin(12345).replace('0b','')
'11000000111001'

3、也可以采用字符串的 format 方法来获取二进制:

>>> "{0:b}".format(12345)
'11000000111001'
>>> 

930Python Number(数字)

abs() 和 fabs() 区别

  • 1、abs()是一个内置函数,而fabs()在math模块中定义的。
  • 2、fabs()函数只适用于float和integer类型,而 abs() 也适用于复数。
>>> abs(-10)
10
>>> fabs(-10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'fabs' is not defined
>>>import math
>>> math.fabs(-10)
10.0
>>>type(abs(-10))
<type 'int'>
>>> type(math.fabs(-10))
<type 'float'>

正如上面显示 abs(-10) 返回的是 10,而math.fabs(-10)返回的是 10.0

>>>type(abs(-10))
<type 'int'>
>>> type(math.fabs(-10))
<type 'float'>
>>>

929Python Number(数字)

Python 用到了一个将一个数字转化为 对应ASCII 的地方。。。 结果习惯性的用了 ‘a’+1 之类的 或者int('a') , 直接报错==后来查了查才知道--- 规则== 用的是 ord('a') 和chr(59) 之类: 记录一下吧 挺常用的

Python 2.7.8 (default, Jun 30 2014, 16:08:48) [MSC v.1500 64 bit (AMD64)] on win  
32  
Type "help", "copyright", "credits" or "license" for more information.  
>>> ord('b')  # convert char to int  
98  
>>> chr(100)  # convert int to char  
'd'  
>>> unichr(100) # return a unicode byte  
u'd'  
>>>

928Python Number(数字)

cmp(x, y) 函数在 python3.x 中不可用,可用以下函数替代:

operator.lt(a, b)           lt(a, b) 相当于 a < b
operator.le(a, b)           le(a,b) 相当于 a <= b
operator.eq(a, b)           eq(a,b) 相当于 a == b
operator.ne(a, b)           ne(a,b) 相当于 a != b
operator.ge(a, b)           gt(a,b) 相当于 a >= b
operator.gt(a, b)           ge(a, b)相当于 a > b

927Python Number(数字)

range()函数

>>> range(1,5)        # 代表从1到5(不包含5)
[1, 2, 3, 4]
>>> range(1,5,2)      # 代表从1到5,间隔2(不包含5)
[1, 3]
>>> range(5)          # 代表从0到5(不包含5)
[0, 1, 2, 3, 4]

注意:默认情况下,range() 的起始值是 0。

>>> for i in range(5) :
...     print(i)
... 
0
1
2
3
4