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

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


Just for the record:

>>> int('55063.000000')Traceback (most recent call last):  File "<stdin>", line 1, in <module>ValueError: invalid literal for int() with base 10: '55063.000000'

Got me here...

>>> int(float('55063.000000'))55063

Has to be used!


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


Pythonic way of iterating over a file and converting to int:

for line in open(fname):   if line.strip():           # line contains eol character(s)       n = int(line)          # assuming single integer on each line

What you're trying to do is slightly more complicated, but still not straight-forward:

h = open(fname)for line in h:    if line.strip():        [int(next(h).strip()) for _ in range(4)]     # list of integers

This way it processes 5 lines at the time. Use h.next() instead of next(h) prior to Python 2.6.

The reason you had ValueError is because int cannot convert an empty string to the integer. In this case you'd need to either check the content of the string before conversion, or except an error:

try:   int('')except ValueError:   pass      # or whatever