int()函数:在python3中,替换了原有的long与long()函数,取而代之的是int型能表示更大的整数。int()函数能将参数转换为int类型数值并返回。
int()函数能接收两个参数,一个代表要操作的值,另一个代表进制,下面是Python帮助文档的部分内容:
>>> help(int)
Help on class int in module builtins:
class int(object)
| int(x=0) -> integer
| int(x, base=10) -> integer
|
| Convert a number or string to an integer, or return 0 if no arguments
| are given. If x is a number, return x.__int__(). For floating point
| numbers, this truncates towards zero.
|
| If x is not a number or if base is given, then x must be a string,
| bytes, or bytearray instance representing an integer literal in the
| given base. The literal can be preceded by '+' or '-' and be surrounded
| by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
| Base 0 means to interpret the base from the string as an integer literal.
| >>> int('0b100', base=0)
| 4
从文档可以看出,当有两个参数时,第一个参数必须当作字符串输入,第二个参数是第一个参数原本的进制;若只有一个参数,默认为十进制,有无”都无所谓。无论如何,该函数返回十进制,下面是几个例子:
>>> int(5.23)
5
>>> int('20')
20
>>> int('20',2)
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
int('20',2)
ValueError: invalid literal for int() with base 2: '20'
>>> int('100',2)
4
>>> int('14',16)
20
在Python2以前,经常使用cmp()函数来比较一些数值,但在新版Python中,已经弃用了这种方式。取而代之的是operator模块中增加了以下函数:
operator.lt(a, b) //a<b
operator.le(a, b) //a<=b
operator.eq(a, b) //a==b
operator.ne(a, b) //a!=b
operator.ge(a, b) //a>=b
operator.gt(a, b) //a>b
operator.__lt__(a, b)
operator.__le__(a, b)
operator.__eq__(a, b)
operator.__ne__(a, b)
operator.__ge__(a, b)
operator.__gt__(a, b)
这几个函数返回都是bool类型,以下是几个例子:
>>> operator.le ('sdss','sssssssss')
True
>>> operator.lt ('ss','sssss')
True
>>> operator.ge(3,5)
False
>>> operator.eq(100,100)
True