python内置int函数详细介绍

英文文档:

class int(x=0) class int(x, base=10)

return an integer object constructed from a number or string x, 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 radix base. optionally, the literal can be preceded by + or – (with no space in between) and surrounded by whitespace. a base-n literal consists of the digits 0 to n-1, with a to z (or a to z) having values 10 to 35. the default base is 10. the allowed values are 0 and 2-36. base-2, -8, and -16 literals can be optionally prefixed with 0b/0b, 0o/0o, or 0x/0x, as with integer literals in code. base 0 means to interpret exactly as a code literal, so that the actual base is 2, 8, 10, or 16, and so that int(‘010’, 0) is not legal, while int(‘010’) is, as well as int(‘010’, 8).

说明:

  1. 不传入参数时,得到结果0。

>>> int()
0

  2. 传入数值时,调用其__int__()方法,浮点数将向下取整。

>>> int(3)3
>>> int(3.6)3

  3. 传入字符串时,默认以10进制进行转换。

>>> int(’36’)36
>>> int(‘3.6’)
traceback (most recent call last):
file “”, line 1, in
int(‘3.6’)
valueerror: invalid literal for int() with base 10: ‘3.6’

  4. 字符串中允许包含”+”、”-“号,但是加减号与数值间不能有空格,数值后、符号前可出现空格。

>>> int(‘+36’)36
>>> int(‘-36’)-36
>>> int(‘ -36 ‘)-36
>>> int(‘ – 36 ‘)
traceback (most recent call last):
file “”, line 1, in
int(‘ – 36 ‘)
valueerror: invalid literal for int() with base 10: ‘ – 36

  5. 传入字符串,并指定了进制,则按对应进制将字符串转换成10进制整数。

>>> int(’01’,2)1
>>> int(’02’,3)2
>>> int(’07’,8)7
>>> int(‘0f’,16)15

以上就是python内置int函数详细介绍的详细内容,更多请关注 第一php社区 其它相关文章!

Posted in 未分类

发表评论