• 技术文章 >Python技术 >Python基础教程

    Python中int()强制类型转换

    2020-10-29 16:49:40原创5631
    小编在学习Python的时候发现了一个有趣的类型转换,今天就分享给大家。

    1

    2

    3

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">a=12.8

    print(type(12.8))

    print(int(12.8))<br></span></p>

    运行结果很明显:

    1

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";"><class 'float'><br>12</span></p>

    接下来就是有些疑惑的地方了。

    1

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">a = input("input:")<br>print(type(a))<br>print(int(a))<br></span></p>

    不同的输入有不同的输出结果,当输入小数时,会报错;当输入整数时却可以正常运行。

    1

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">input:12.8<br><class 'str'><br>Traceback (most recent call last):<br>  File "D:/PycharmProject/Study/Chapter3.py", line 66, in <module><br>    print(int(a))<br>ValueError: invalid literal for int() with base 10: '12.8'<br></span></p>

    1

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">input:12<br><class 'str'><br>12<br></span></p>

    一个方法是:

    1

    2

    3

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">a = input("input:")

    print(type(a))

    print(int(float(a)))<br></span></p>

    将类型进行两次转换,得到了想要的结果:

    1

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">input:12.8<br><class 'str'><br>12<br></span></p>

    也有人给出了更好的办法:

    1

    2

    3

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">a = eval(input("input:"))

    print(type(a))

    print(int(a))<br></span></p>

    得到的结果:

    1

    <p style="line-height: 1.75em;"><span style="font-family: 微软雅黑, "Microsoft YaHei";">input:12.8<br><class 'float'><br>12<br></span></p>

    两种方法都分享给大家,根据适合自己的随便挑选。更多Python学习推荐:PyThon学习网教学中心

    专题推荐:int强制类型转换;python
    上一篇:Python教程:int()函数的用法解析 下一篇:Python基础之list列表读取文件的方法

    相关文章推荐

    • 在python里int是什么意思• python中的int函数是什么意思• python如何判断输入参数是int类型的• python定义int型变量吗?• python3与2中print有什么区别?• python怎么把int类型转换成列表• python3中怎么让print输出不换行• Python教程:int()函数的用法解析

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网