Python 内建函数 - int(x=0)

本文介绍了Python的内建函数int,用于将数字或字符串转换为整数。当无参数时,它返回0;对于浮点数,它进行零截断。int函数接受一个可选的基数参数,允许解析不同基数的数字字面量,包括二进制、八进制、十六进制。从Python 3.4开始,如果基数不是一个整数,会尝试调用其__index__方法。示例展示了int函数的不同用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参数形式

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

Manual

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).

The integer type is described in Numeric Types — int, float, complex.

Changed in version 3.4: If base is not an instance of int and the base object has a base.__index__ method, that method is called to obtain an integer for the base. Previous versions used base.__int__ instead of base.__index__.

直译

根据数字或字符串x构造一个整数对象,若未给定参数则返回0。如果x是数字,则返回x.__int__()。对于浮点数,会直接截断为0。
如果x是非数值或给定base,那么x必须是在其基数base上,可以用来表示整数字面的string、bytes或bytearray的实例。字面可以选择+或-(中间不空格)做前缀,由空格环绕。n位基数字面包含数字0到n-1,同时a到z(或A到Z)表示的值为10到35。默认的base是10,其允许的值域为0和2-36。如同代码中的整数字面,基数2、8和16位字面可选用0b/0B、0o/0O或0x/0X作为前缀。基数0表示精确的解释成一个代码字面,那么实际中的基数是2、8、10或16,以致于int(‘010’, 0)是非法的,然而int(‘010’)等同于int(‘010’, 8)。
整数类型详情见数字类型 — 整数、浮点数和复数

version 3.4变更:如果base不是整数实例,且base对象有base.__index__方法,那么会调用该方法来获取一个整数,前一个版本使用的是base.__int__。

实例

# 字符串
>>> int('10')
10
# 浮点数
>>> int(3.14)
3
# bytes对象
>>> int(b'10')
10
# 16进制
>>> int('0xa', 16)
10
# 8进制
>>> int('0o12', 8)
10
# 2进制
>>> int('1010', 2)
10

拓展阅读

数字类型 — 整数、浮点数和复数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值