Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to fix this ValueError invalid literal for int with base 10 error in Python

I am creating a program that reads a file and if the first line of the file is not blank, it reads the next four lines. Calculations are performed on those lines and then the next line is read. If that line is not empty it continues. However, I am getting this error:

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

It is reading the first line but can't convert it to an integer.

What can I do to fix this problem?
by

3 Answers

espadacoder11
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:

Hope it helps!!

If you need to know more about Python, It's recommended to join Python course today.

Thanks!
sandhya6gczb
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!
pankajshivnani123
Python generates the error message you present in your question whenever you call the int() builtin function with a string argument that cannot be parsed as an integer; and, in fact, the error message shows you the precise string it was trying to parse as an integer: namely ‘0.25’.

How to fix the error? It depends on what you want to do.

If what you want is to parse and convert the string to a numeric value, this particular string clearly contains a numeric representation which is not an integer but a real. The way to “fix” the error in this case is to invoke the float() builtin function, which returns a floating point (real) value. If you really wanted an integer, despite having a real in the string, use int(float(your_value_here)). Note that this converts the string to a floating point value, which is then converted to an integer via truncation—that is, by discarding the fractional part. Applying these functions to ‘0.25’ will produce a result of 0. If, on the other hand, you wanted the floating point value, just use float().

Or, perhaps, you didn’t expect the ‘0.25’. In this case, find where that string comes from and fix the problem at the origin. Can’t help you there, though, as I don’t know your code and how that string got to the int() call.

Login / Signup to Answer the Question.