2

Unable to convert a string to an integer. Getting Error:

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

I have read many answers and most of them the reason for not working is because it is a float and people use int(), but here clearly it is an integer.

like1 = '2,674 likes'
number = int(like1.split()[0])
print('This is the numer ::',number)

I expect the code to run without an error and print out the number. My actual implementation is to compare it with an integer. For eg. number > 1000, but that throws up the error that you can't compare a string and int, therefore I wanted to modify it into an int. I did not want to post that code since it was pretty big and messy.

Please ask for clarifications, if I have missed any required details!

Shawn
  • 261
  • 1
  • 7
  • 25
  • replace comma with dot: `int(like1.split()[0].replace(',', '.'))` – Radosław Cybulski Jun 09 '19 at 08:01
  • @RadosławCybulski, replacing comma with a dot makes a huge difference. Probably, you might have meant replacing with empty string. – Austin Jun 09 '19 at 08:10
  • @RadosławCybulski As Austin said, replacing it with a dot did make a big difference. Removing the comma worked fine – Shawn Jun 09 '19 at 08:25
  • You are never supposed to post your full code on Stack Overflow; you are expected to trim it down to a [mre]. – tripleee Jun 09 '19 at 08:25

1 Answers1

2

Your problem is the comma in 2,674. Some locations use that as a decimal point, but your location does not, and you want it to separate groups of three digits in an integer. Python does not use it in that way.

So either remove the comma or change it to an underscore, _, which recent versions of Python allow in an integer. Since I do not know your version of Python I recommend removing the comma. Use this:

number = int(like1.split()[0].replace(',', ''))

By the way, the error message you show at the top of your question is not the actual error message. The actual message shows the comma in the string:

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

If you continue asking questions on this site, be sure to show the actual errors. In fact, you should copy and paste the entire traceback, not just the final line. That will help us to correctly understand your problem and help you.

Rory Daulton
  • 21,934
  • 6
  • 42
  • 50
  • Thank You, Rory, Sure I will do that. Was confused whether t include the entire error since it said to make it 'concise'. Will change it next time:) – Shawn Jun 09 '19 at 08:22