python 如何将带小数的浮点型字符串转换为整数
作者:哦摩西罗伊 时间:2021-04-24 01:35:51
以下内容在python中完全可以接受:
1、将整数的字符串表示形式传递给 int
2、将float的字符串表示形式传递给 float
但是,如果你将float型的字符串传递给int将会得到错误。
>>> int('5')
5
>>> float('5.0')
5.0
>>> float('5')
5.0
>>> int(5.0)
5
>>> float(5)
5.0
>>> int('5.0')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.0'
>>> int(float('5.0'))
补充:解决python 字符串浮点型转整型问题
ValueError: invalid literal for int() with base 10
复原错误:
str_a = '1.5'
int_a = int(str_a)
修正错误:
# 修正方式1
str_a = '1.5'
int_a = int(float(str_a))
# 修正方式2
str_a = '1.5'
int_a = int(eval(str_a))
错误原因
浮点型字符串无法直接转int类型
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。如有错误或未考虑完全的地方,望不吝赐教。
来源:https://www.cnblogs.com/mlgjb/p/11170331.html
标签:python,小数,浮点型,字符串,整数
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python运行DLL文件的方法
2021-12-25 15:23:21
pygame学习笔记(5):游戏精灵
2021-10-13 18:29:56
![](https://img.aspxhome.com/file/2023/2/86492_0s.jpg)
Python入门教程(三十六)Python的文件写入
2023-04-30 11:27:48
![](https://img.aspxhome.com/file/2023/1/97031_0s.jpg)
Python如何利用IMAP实现邮箱客户端功能
2023-11-08 22:23:56
![](https://img.aspxhome.com/file/2023/6/66366_0s.jpg)
django2.0扩展用户字段示例
2023-08-31 11:10:10
Python爬取肯德基官网ajax的post请求实现过程
2021-03-31 13:54:00
![](https://img.aspxhome.com/file/2023/5/104815_0s.jpg)
numpy np.newaxis 的实用分享
2023-01-21 06:06:25
Python使用turtle库绘制小猪佩奇(实例代码)
2021-09-21 08:45:30
![](https://img.aspxhome.com/file/2023/5/72135_0s.jpg)
python实现web方式logview的方法
2023-12-23 17:07:54
在Python中使用Mako模版库的简单教程
2021-11-08 12:33:45
mcrypt启用 加密以及解密过程详细解析
2023-07-15 19:41:55
解决golang编译提示dial tcp 172.217.160.113:443: connectex: A connection attempt failed(推荐)
2023-07-16 04:24:49
python删除文件、清空目录的实现方法
2021-06-02 02:53:06
PHP的mysqli_stat()函数讲解
2023-06-12 08:11:33
![](https://img.aspxhome.com/file/2023/5/55455_0s.png)
Python打包工具PyInstaller的安装与pycharm配置支持PyInstaller详细方法
2022-05-20 06:36:55
![](https://img.aspxhome.com/file/2023/3/107133_0s.png)
使用Abot中文分词组件来开发ASP站内搜索引擎
2007-10-18 13:36:00
月影:JavaScript王者归来
2008-08-05 17:18:00
![](https://img.aspxhome.com/file/UploadPic/20088/5/200885172229312s.jpg)
python函数超时自动退出的实操方法
2021-09-11 07:07:45
Python趣味挑战之用pygame实现飞机塔防游戏
2022-07-18 04:00:02
![](https://img.aspxhome.com/file/2023/7/95867_0s.gif)
用 AjaxTags 简化 Ajax 开发
2007-11-27 00:00:00