Python笔记(一)——int(),operator比较数值

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值