Python内置int函数详细介绍

高洛峰
发布: 2017-03-21 09:33:57
原创
2303人浏览过

英文文档:

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 "<pyshell#2>", line 1, in <module>
    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 "<pyshell#7>", line 1, in <module>
    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中文网其它相关文章!

python速学教程(入门到精通)
python速学教程(入门到精通)

python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号