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

系统管理员 2021-09-27 14:32 355阅读 0赞

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:

  1. int("5")
  2. 5
  3. float("5.0")
  4. 5.0
  5. float("5")
  6. 5.0
  7. int(5.0)
  8. 5
  9. float(5)
  10. 5.0
  11. int("5.0")
  12. Traceback (most recent call last):
  13. File "<input>", line 1, in <module>
  14. ValueError: invalid literal for int() with base 10: '5.0'

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

发表评论

表情:
评论列表 (有 0 条评论,355人围观)

还没有评论,来说两句吧...

相关阅读