713

I got this error from my code:

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

What does it mean? Why does it occur, and how can I fix it?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Sarah Cox
  • 7,155
  • 3
  • 16
  • 3
  • 3
    For anyone currently looking here. The error may be that one of the lines isn't in integer form. Eg: "yes" isn't in the correct form but "3" is. For this question the first line may not have any "1"s, "2"s, "3"s... to convert to an int. – Crupeng Jul 24 '20 at 17:58
  • 2
    i got this error when input string had space between digits. this error basically means your input string is not valid for string to integer conversion. for conversion, your string should only and only contain following characters: +-.0123456789 – MbPCM Aug 05 '20 at 12:41

17 Answers17

819

The error message means that the string provided to int could not be parsed as an integer. The part at the end, after the :, shows the string that was provided.

In the case described in the question, the input was an empty string, written as ''.

Here is another example - a string that represents a floating-point value cannot be converted directly with int:

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

Instead, convert to float first:

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

See:https://www.geeksforgeeks.org/python-int-function/

Mig82
  • 4,856
  • 4
  • 40
  • 63
FdoBad
  • 8,247
  • 1
  • 13
  • 2
  • 155
    I'll just add, to provide more clarity for future readers, that indeed, int(float('1.0')) works when int('1.0') throws the ValueError. – katyhuff Apr 26 '13 at 16:53
  • 8
    This should be the accepted top answer to this question. I almost closed the page and didn't see it. Thanks! – iTurki Jun 21 '16 at 21:44
  • 4
    add to answer int(float('55063.000000')) as question is get int(). Than it will realy top answer – Max Mar 15 '17 at 08:41
  • 3
    Why does this happen? @katyhuff – Muhamed Huseinbašić Jun 08 '17 at 14:03
  • 1
    Why not update your answer as per @Kevin's comment above? This is a highly active question and should not be confusing to someone who directly search for the specific error in question title. – Austin Jun 29 '20 at 04:17
  • I think it is quite easy to handle the empty string case, just check if len(str) !=0 – Anshuman Kumar Jul 21 '20 at 07:50
  • 8
    when I'm converting a string to float according to the above answer, it says `ValueError: could not convert string to float:` – y_159 Sep 27 '20 at 07:30
  • `int(float(some_float_str))` is what I've been doing already, but I looked this up to see if there was a more idiomatic way, haven't seen any better alternative here... but it works! – Nagev Apr 11 '21 at 17:17
  • This should not happen, but it does. Feel free to educate me on the usefulness of this. – JohnAllen Jun 16 '22 at 04:50
  • What if i would need to work with a single decimal number? For example '593450.50000' – toms Feb 15 '23 at 09:27
167

The following work fine in Python:

>>> int('5') # passing the string representation of an integer to `int`
5
>>> float('5.0') # passing the string representation of a float to `float`
5.0
>>> float('5') # passing the string representation of an integer to `float`
5.0
>>> int(5.0) # passing a float to `int`
5
>>> float(5) # passing an integer to `float`
5.0

However, passing the string representation of a float, or any other string that does not represent an integer (including, for example, an empty string like '') will cause a ValueError:

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

To convert the string representation of a floating-point number to integer, it will work to convert to a float first, then to an integer (as explained in @katyhuff's comment on the question):

>>> int(float('5.0'))
5
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Peter
  • 1,983
  • 1
  • 12
  • 9
  • 3
    Wow that's incredibly silly. Why not make int() accept a string? That's exactly what I was expecting it to do and not typecast it into float first..... – BUFU Sep 22 '20 at 11:57
  • typecasting into float doesn't work in my case at least.. error shown is couldnot convert int to float – Alex Jul 13 '21 at 22:33
  • 1
    @BUFU it **does** accept a string. As long as that string represents an integer. – Karl Knechtel Jan 14 '23 at 03:45
  • @Alex the technique here is to convert a **string that represents a float**, to a float first, and then to an int. If your error says that it could not convert an int to a float, this implies that you **already have** an int. If your goal is to have an int, then the correct code is none at all. – Karl Knechtel Jan 14 '23 at 03:46
  • @KarlKnechtel I **obviously** meant a string representing a float... – BUFU Jan 15 '23 at 13:18
  • Ah. In that case, the best I can offer is: Python's philosophy is that there are no "casts", only conversions (i.e., creation of a new value). Since "explicit is better than implicit" and "errors should never pass silently unless explicitly silenced", the conversion string->float->int is forced to occur in two steps - in order to make sure that the programmer acknowledges "yes, I want to discard the fractional part, if any". – Karl Knechtel Jan 16 '23 at 05:01
  • Converting to `int` entails that a floating-point value wouldn't make sense; therefore, if the user tried to provide a floating-point value, there's a good chance that *the user misunderstands the purpose of the data, and has input something nonsensical*. – Karl Knechtel Jan 16 '23 at 05:01
  • If you pass a variable into `int()`, you always explicitly discard the fractional part of any value (after all, there is the option to use `float()`. It accepts strings, it accepts floats, but it does not accept a string of a float... It doesn't make sense to me. But I guess as long as it's consistent in this behaviour, it's fine. Just one more grammar rule for this language. – BUFU Jan 17 '23 at 21:42
  • @KarlKnechtel "Converting to int entails that a floating-point value wouldn't make sense" - well, now you're being silly. If that was true, it wouldn't accept a float - which it does. Providing a float into `int()`, there is a good chance the user wants to discard the decimals and have a whole number. (A very good reason to use `int()` and not `float()`.) – BUFU Jan 17 '23 at 21:48
  • Converting to int **from a string** entails that a string **representing a floating-point value** wouldn't make sense. This is because the **reason** that we do these conversions from string, primarily, is to process user input, not to e.g. round off numeric calculations to the nearest pixel. – Karl Knechtel Jan 18 '23 at 04:23
  • @KarlKnechtel Converting to int **from any value in any form** should simply give you the best guess of which integer is meant from the value. the string "5.0" is indeed an integer represented by a string, not a floating-point value. a decimal point doesn't make the difference, the value does. But besides that, I would even argue that the string "5.2" should give you an int of value 5. Because we mainly do these conversions to get to the right variable type to put into some function. – BUFU Jul 03 '23 at 21:51
71

int cannot convert an empty string to an integer. If the input string could be empty, consider either checking for this case:

if data:
    as_int = int(data)
else:
    # do something else

or using exception handling:

try:
    as_int = int(data)
except ValueError:
    # do something else
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
30

Python will convert the number to a float. Simply calling float first then converting that to an int will work: output = int(float(input))

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Brad123
  • 877
  • 10
  • 10
18

This error occurs when trying to convert an empty string to an integer:

>>> int(5)
5
>>> int('5')
5
>>> int('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Joish
  • 1,458
  • 18
  • 23
13

The reason is that you are getting an empty string or a string as an argument into int. Check if it is empty or it contains alpha characters. If it contains characters, then simply ignore that part.

Toluwalemi
  • 391
  • 5
  • 16
rajender kumar
  • 412
  • 3
  • 12
12

Given floatInString = '5.0', that value can be converted to int like so:

floatInInt = int(float(floatInString))
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Hrvoje
  • 13,566
  • 7
  • 90
  • 104
3

You've got a problem with this line:

while file_to_read != " ":

This does not find an empty string. It finds a string consisting of one space. Presumably this is not what you are looking for.

Listen to everyone else's advice. This is not very idiomatic python code, and would be much clearer if you iterate over the file directly, but I think this problem is worth noting as well.

jcdyer
  • 18,616
  • 5
  • 42
  • 49
  • This is unrelated to the question being asked and which remains after proper editing. We see here the perils of failing to insist on [mre]s. Of course, standards were very different in 2009. – Karl Knechtel Jan 14 '23 at 03:53
2

My simple workaround to this problem was wrap my code in an if statement, taking advantage of the fact that an empty string is not "truthy":

Given either of these two inputs:

input_string = ""    # works with an empty string
input_string = "25"  # or a number inside a string

You can safely handle a blank string using this check:

if input_string:
   number = int(input_string)
else:
   number = None # (or number = 0 if you prefer)

print(number)
Allen Ellis
  • 269
  • 2
  • 9
1

I recently came across a case where none of these answers worked. I encountered CSV data where there were null bytes mixed in with the data, and those null bytes did not get stripped. So, my numeric string, after stripping, consisted of bytes like this:

\x00\x31\x00\x0d\x00

To counter this, I did:

countStr = fields[3].replace('\x00', '').strip()
count = int(countStr)

...where fields is a list of csv values resulting from splitting the line.

T. Reed
  • 181
  • 1
  • 9
0

This could also happen when you have to map space separated integers to a list but you enter the integers line by line using the .input(). Like for example I was solving this problem on HackerRank Bon-Appetit, and the got the following error while compiling enter image description here

So instead of giving input to the program line by line try to map the space separated integers into a list using the map() method.

Amit Kumar
  • 804
  • 2
  • 11
  • 16
  • The underlying problem here is a different one; please see [Get a list of numbers as input from the user](https://stackoverflow.com/questions/4663306). – Karl Knechtel Jan 14 '23 at 03:54
0

This seems like readings is sometimes an empty string and obviously an error crops up. You can add an extra check to your while loop before the int(readings) command like:

while readings != 0 or readings != '':
    readings = int(readings)
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Kanishk Mair
  • 333
  • 1
  • 4
  • 8
0

your answer is throwing errors because of this line

readings = int(readings)
  1. Here you are trying to convert a string into int type which is not base-10. you can convert a string into int only if it is base-10 otherwise it will throw ValueError, stating invalid literal for int() with base 10.
shubham
  • 56
  • 6
0

Landed here as I had this problem but with pandas Dataframes. I had int values stored as 12345.0.

The same solution applies in pandas (I believe it would work in numpy with ndarrays as well) :

df["my_int_value"] = df["my_string_value"].astype(float).astype(int)
Théo Rubenach
  • 484
  • 1
  • 4
  • 12
0

This error sometimes shows up when changing the dtype of a pandas column using astype(int). The astype() method raises ValueError: invalid literal for int() with base 10: '' for the very same reason that is detailed on many answers here.

In such cases, if you want the empty string '' parsed as a missing value aka NaN, then use to_numeric instead of astype() and the error goes away.

import pandas as pd

df = pd.DataFrame({'col': ['1', '2', '']})

df['col'] = df['col'].astype(int)      # ValueError: invalid literal for int() with base 10: ''

df['col'] = pd.to_numeric(df['col'])   # OK (the empty string is parsed as NaN)
cottontail
  • 10,268
  • 18
  • 50
  • 51
-1

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.

Something like this should work:

for line in infile:
    next_lines = []
    if line.strip():
        for i in xrange(4):
            try:
                next_lines.append(infile.next())
            except StopIteration:
                break
    # Do your calculation with "4 lines" here
Imran
  • 87,203
  • 23
  • 98
  • 131
-1

Another answer in case all of the above solutions are not working for you.

My original error was similar to OP: ValueError: invalid literal for int() with base 10: '52,002'

I then tried the accepted answer and got this error: ValueError: could not convert string to float: '52,002' --this was when I tried the int(float(variable_name))

My solution is to convert the string to a float and leave it there. I just needed to check to see if the string was a numeric value so I can handle it correctly.

try: 
   float(variable_name)
except ValueError:
   print("The value you entered was not a number, please enter a different number")
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • The problem description here does not make sense. Converting from float to int will not fail in ordinary cases, and is demonstrably not what failed in the examples. The underlying problem is that neither `int` nor `float` supports thousands separators by default. See [How can I convert a string with dot and comma into a float in Python](/questions/6633523) and [How to convert a string to a number if it has commas in it as thousands separators?](/questions/1779288). – Karl Knechtel Jan 14 '23 at 03:58