python ValueError: invalid literal for int() with base 10: ''

本文详细介绍了Python中不同类型之间的转换规则,包括字符串转整数、浮点数,浮点数转整数,以及可能引发的ValueError错误。文章通过具体示例展示了如何避免常见错误,并提供了正确的转换方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The following are totally acceptable in python:

  • passing a string representation of an integer into int
  • passing a string representation of a float into float
  • passing a string representation of an integer into float
  • passing a float into int
  • passing an integer into float

But you get a ValueError if you pass a string representation of a float into int, or a string representation of anything but an integer (including empty string). If you do want to pass a string representation of a float to an int, as @katyhuff points out above, you can convert to a float first, then to an integer:

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 "<input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.0'

参考:ValueError: invalid literal for int() with base 10: ''

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值