Python中如何使用int()

发布时间:2020-12-07 09:48:54 作者:小新
来源:亿速云 阅读:534

小编给大家分享一下Python中如何使用int(),希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!

Python int()使用小结

int()的基本语法格式是int(x,[base=10]),其中base可以省略

int()的作用是把不同进制的数字或数字字符串转为十进制整数。使用中,其行为,参数有一些tricky,需要特别注意。

不带参数返回0,即int()

>>> int()
0

取整是简单截断,不是四舍五入,如int(1.5) = 1

>>> int(1.5)
1

参数可以是整数,浮点数,或算术表达式如100/3,但不能是复数,如1+2j

>>> int(3)
3
>>> int(3.5)
3
>>> int(100/3)
33
>>> int(1+2j)
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    int(1+2j)
TypeError: can't convert complex to int

数字字符串可以是整数字符串如’123’,但不能是算术表达式字符串如’100/3’,或字符形式的浮点数如’1.5’

>>> int('123')
123
>>> int(100/3)
33
>>> int('100/3')
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    int('100/3')
ValueError: invalid literal for int() with base 10: '100/3'
>>> int('1.5')
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    int('1.5')
ValueError: invalid literal for int() with base 10: '1.5'

base缺省值是10,表示十进制,如果包括base参数,则前面的x必须是符合当前进制的数字字符串
此时int的作用是把base进制代表的数字字符串x,转换为10进制数

>>> int('45',8)# 把8进制'45'转换为十进制数37
37

>>> int('ab',16) #
171

>>> int(45,8)
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    int(45,8)
TypeError: int() can't convert non-string with explicit base
>>> int(ab,16)
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    int(ab,16)
NameError: name 'ab' is not defined

看完了这篇文章,相信你对Python中如何使用int()有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

推荐阅读:
  1. python Web开发的参考书
  2. 【问题】spark运行python写的mapreduce任务,hadoop平台报错,java.net.ConnectException: 连接超时

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python int()

上一篇:python中用while语句将二进制转化为十进制的方法

下一篇:Python中将int转换为String的方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》