The error ValueError: invalid literal for int() with base 10 occurs when Python's int() function is passed a string that cannot be interpreted as a valid integer.

Common Causes

  • Non-numeric characters: The string contains letters, symbols, or spaces (e.g., "abc", "123.45", " 42 ").

  • Floating-point numbers: Strings with decimal points (e.g., "5.20") cannot be directly converted to integers.

  • Empty or whitespace-only strings: An empty string ('') or string with only spaces (" ") is invalid.

  • Scientific notation: Strings like "3.2e+07" are not valid for int().

  • Non-integer input from user or file: User input or data from a file may not be in the expected format.

Solutions

1. Use float() first, then int()

If the string represents a decimal number, convert it to a float first, then to an integer:

num_str = "5.20"
result = int(float(num_str))  # Output: 5

2. Use try-except to handle errors gracefully

Wrap the conversion in a try-except block to prevent crashes:

try:
    value = int("abc123")
except ValueError:
    print("Invalid input: not a valid integer")

3. Validate input with isdigit()

Check if the string contains only digits before conversion:

text = "123"
if text.isdigit():
    num = int(text)
else:
    print("Input is not a valid integer")

⚠️ Note: isdigit() returns False for negative numbers ("-123") or decimals.

4. Strip whitespace

Remove leading/trailing spaces using .strip():

text = "  42  "
num = int(text.strip())  # Output: 42

5. Handle empty strings in pandas

When using pandas, avoid astype(int) on columns with empty strings. Use pd.to_numeric() instead:

df['col'] = pd.to_numeric(df['col'], errors='coerce')  # Converts empty strings to NaN

Summary

Always ensure the input string is a valid integer representation before calling int(). Use float() + int() for decimals, try-except for safety, and strip() or isdigit() for validation.

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
Answer from FdoBad on Stack Overflow
Top answer
1 of 16
928

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
2 of 16
181

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
🌐
Reddit
reddit.com › r/learnpython › how to fix the 'valueerror: invalid literal for int() with base 10:’ error
How to fix the 'ValueError: invalid literal for int() with base ...
June 23, 2022 -

While trying to convert an input string into an integer, I got a Traceback and an error saying 'ValueError: invalid literal for int() with base 10:<string>'. for context, here's the code I was trying to run --

x = None
print("FINDING THE SMALLEST NUMBER from 90, 7089, 54, 678, 6703, 12, 5544, 8989, 9099, 746, 389, 34, 22, 909, 8787, 9976, 543, 898, 9098, 4784")
for ival in [90, 7089, 54, 678, 6703, 12, 5544, 8989, 9099, 746, 389, 34, 22, 909, 8787, 9976, 543, 898, 9098, 4784]:

if x == None:
x = ival
elif ival < x:
x = ival

print("The smallest number has been succesfully found!")
print("Type 'Yes' to view it, and 'No' to not view it.")

red = int(input("Enter here: "))
if red == Yes:
print(x)
elif red == No:
print("Fine then...")
else:
print("Please enter a valid input.")

I tried to fix the issue by first converting the string to a float and then an int, but it still didn't work. Tried searching for a solution on the net, but the only option I could find was a try-except block. And I don't wanna use that. I just want to fix this so that, I type 'Yes' and it shows me the number. But I am still a newbie in all this and don't know that much, tbh.

🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-fix-valueerror-invalid-literal-for-int-with-base-10-in-python
How to fix "ValueError: invalid literal for int() with base 10" in Python - GeeksforGeeks
April 28, 2025 - Example 2: In this example, we try to convert the string " 4 2 " to an integer using int(), but it contains extra spaces within the number, making it an invalid base-10 format and resulting in a ValueError. ... Hangup (SIGHUP) Traceback (most recent call last): File "/home/guest/sandbox/Solution.py", line 1, in <module> a = int(" 4 2 ") ValueError: invalid literal for int() with base 10: ' 4 2 '
🌐
Reddit
reddit.com › r/learnpython › [valueerror: invalid literal for int() with base 10: "\n"] when working with running through files
r/learnpython on Reddit: [ValueError: invalid literal for int() with base 10: "\n"] When Working With Running Through Files
May 1, 2024 -

I spent way too long working this one out, so here it is:

This was a test for if I can run a function through a function, and it gets the total of a list.

file = open("numbers.txt", "r")

read_file = file.read()
def iterate_through_file(f, fx):
    
    for c in range(len(f)):
         = f[c]
        fx(temporary_value_store)
   

def total(tvs):
    tvs = int(tvs)
    global running_total 
    running_total += tvs
    #return tvs

#main
running_total = 0
iterate_through_file(read_file, total)
print(running_total)

Initially, everything looks fine. Why isn't it working?

The error is passing on the line:

tvs = int(tvs)

But there is nothing wrong with it. The error reads:

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

We notice it says "\n". This is an invisible character called a whitespace that is essentially saying:

"Don't put the next character here, put it down there, one line below."

In text files, this is also the case. If i had a text file of:

1
2
3
4

There is an invisible:

1\n
2\n
3\n
4

Which tells me to "go down to that next line and put the number there".

So, what python has done is read the list, but included these \n's.

So how do we combat this? Very easy.

Firstly, I am aware of the .strip() method, but the reason that does not work is because it removes only from the START and END of a variable. We are trying to remove from inside the variable.

So we will use the .split() function.

The split function takes a variable and turns it into a list. In our original variable, the variable counted \n as an index. So when we loop through this variable, our second index of 1 will have the string "\n". The error now comes from when we try to cast this from a string to an integer inside the def total().

If we split the variable into a list, the list will ignore the \n. This is because whitespaces are how .split() knows where to split. It will find the \n and look at the string before it, then ignore the \n. Its like if you had a line of bricks you want to count, and you want to mark every 5 bricks with a red one so it makes it easier to count. You wouldn't count the red ones in your total, but they are still there to signify every 5th brick.

SO:

Now we know that the problem is because of the "\n" whitespaces, and we know we can get around it with .split().

We do this by:

file = open("numbers.txt", "r")

read_file = file.read()
lines = []
lines = read_file.split()

This creates an array called lines, and splits read_file into it.

We run this, and our code works!

That's the end. Forgive me if I have used incorrect terminology.

Feel free to notify me and I will work on it!

Also please provide feedback if you want to. I am still a historically bad explainer despite a certain commenters words from my last post.

Here is the full code if you want to try it out:

#loop through a file of numbers and find the; total, average, highest and lowest, and how many even and odds there are, using as many robust program concepts as possible
#open file for reading
file = open("numbers.txt", "r")
#read file line by line
read_file = file.read()
lines = []
lines = read_file.split()
#function takes 2 parameters, the read file, and a function
def iterate_through_file(f, fx):
    #running_total = 0
    for c in range(len(f)):
        temporary_value_store = f[c]
        fx(temporary_value_store)
    #return running_total  

def total(tvs):
    tvs = int(tvs)
    global running_total 
    running_total += tvs
    #return tvs

#main
running_total = 0
iterate_through_file(lines, total)
print(running_total)

Also, I know I posted 3 times in like 3 days, but I am not one of those coding guys who cannot figure out a problem without stack overflow and an iced coffee, but still spend all day with a hunchback at their desk coding like it's their job (It probably is).

I felt I needed to say this because posting this much makes me out to be one of those guys. Coding is for fun.

Anyway, hope this helps someone out there!

Have A Good One,

Hawk

Find elsewhere
🌐
Esri Community
community.esri.com › t5 › python-questions › invalid-literal-for-int-with-base-10 › td-p › 556849
Solved: Invalid literal for int() with base 10. - Esri Community
July 24, 2013 - Your variables in Quakesim_List are strings, hence the failure. int(max(float(sim) for sim in Quakesim_List)) Do that.
🌐
Koladechris
koladechris.com › blog › valueerror-invalid-literal-for-int-with-base-10-in-python-fixed
ValueError: invalid literal for int() with base 10: in Python [Fixed]
December 26, 2022 - Hence, such a number is not in base 10. This means you cannot convert a floating point number formatted as a string to an integer with the int() method. To fix this error, Python provides a method for converting such numbers formatted as a string – the float() method.
🌐
Dataquest Community
community.dataquest.io › q&a › dq courses
Invalid literal for int() with base 10: 'H' - DQ Courses - Dataquest Community
September 17, 2019 - Hi All, i am trying to convert string values into integer but i am unable to do so. Kindly help me out. attaching you the code and error screenshot. Code :- Calculate the average number of comments Ask HN posts receive. total_ask_comments = 0 for post in ask_posts: total_ask_comments += int(post[4]) avg_ask_comments = total_ask_comments / len(ask_posts) print(avg_ask_comments) total_show_comments = 0 for post in show_posts: total_show_comments += int(post[4]) avg_show_comments = tota...
🌐
DEV Community
dev.to › itsmycode › valueerror-invalid-literal-for-int-with-base-10-4klg
ValueError: invalid literal for int() with base 10 - DEV Community
September 7, 2021 - ValueError: invalid literal for int() with base 10 occurs when you convert the string or decimal or characters values not formatted as an integer.
🌐
PyTorch Forums
discuss.pytorch.org › nlp
Torchtext error: ValueError: invalid literal for int() with base 10: 'Sentiment' - nlp - PyTorch Forums
April 6, 2019 - I was trying to create a classifier model using the Amazon fine food reviews dataset that can be obtained from Kaggle. But the training of the LSTM model is failing with the below error --------------------------------------------------------------------------- ValueError Traceback (most recent ...
🌐
GitHub
github.com › mapillary › seamseg › issues › 14
ValueError: invalid literal for int() with base 10: '' · Issue #14 · mapillary/seamseg
January 6, 2020 - Traceback (most recent call last): ...3.6/configparser.py", line 803, in _get return conv(self.get(section, option, **kwargs)) ValueError: invalid literal for int() with base 10: '' return conv(self.get(section, option, **kwargs)) ValueError: invalid literal for int() with base ...
Author   sameer56
🌐
PyTorch Forums
discuss.pytorch.org › nlp
ValueError: invalid literal for int() with base 10: '-3.21588' - nlp - PyTorch Forums
April 12, 2024 - Sorry, I am kind of a total beginner at this stuff, so please bear with me. I’m trying to train an NMT model FR-EN but I keep getting this error. Code: !onmt_train -config config.yaml Error: File “/usr/local/lib/python3.10/dist-packages/onmt/inputters/inputter.py”, line 282, in _load_vocab counters[name][token] = int(count) ValueError: invalid literal for int() with base 10: ‘-3.21588’ I looked through the files and the -3.21588 comes from the source.model file.
🌐
Python Forum
python-forum.io › thread-20300.html
ValueError: invalid literal for int() with base 10: ''
Hi I have the following text file that I have uploaded here: This data sits in a larger data set in a text file but I have just extracted the set of data I am interested in and uploaded it into a separate text file. Data Instead of reading these a...
🌐
Bioinformatics Answers
biostars.org › p › 451962
Deeptools ValueError: invalid literal for int() with base 10 ...
July 28, 2020 - The error message invalid literal for int() with base 10 would seem to indicate that you are passing a string that's not an integer to the int() function . In other words it's either empty, or has a character in it other than a digit. You can solve this error by using Python isdigit() method ...
🌐
Home Assistant
community.home-assistant.io › configuration
How do i fix numerical_value = int(value) ^^^^^^^^^^ ValueError: invalid literal for int() with base 10: '' - Configuration - Home Assistant Community
August 17, 2023 - i get this error in the logs… its complaining about the value? just not sure how u fix that not sure where to look? Logger: homeassistant.helpers.event Source: components/sensor/__init__.py:595 First occurred: 12:15:00 PM (1 occurrences) Last logged: 12:15:00 PM Error while dispatching event ...