Python int()使用小结

2025-12-01 0 46,991

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 "", line 1, in 
    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 "", line 1, in 
    int('100/3')
ValueError: invalid literal for int() with base 10: '100/3'
>>> int('1.5')
Traceback (most recent call last):
  File "", line 1, in 
    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 "", line 1, in 
    int(45,8)
TypeError: int() can't convert non-string with explicit base
>>> int(ab,16)
Traceback (most recent call last):
  File "", line 1, in 
    int(ab,16)
NameError: name 'ab' is not defined

本文转载自:https://blog.csdn.net/

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:以上部本文内容由互联网用户自发贡献,本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。投诉邮箱:3758217903@qq.com

ZhiUp资源网 python基础 Python int()使用小结 https://www.zhiup.top/3204.html

相关