-2

I have a number of type string with single quotes. e,g

var = '2,000'
type(var) # <class 'str'>

I want to convert it to int.

I have tried int(var) But it gives an error

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

keerthan kumar
  • 332
  • 7
  • 25
  • 2
    You have a `,` in your string, you need to remove it before you can convert – user3483203 May 18 '18 at 05:18
  • Take a look at this question :) : https://stackoverflow.com/questions/2953746/python-parse-comma-separated-number-into-int – rafaelc May 18 '18 at 05:19
  • 1
    BTW, you actually lied in the question, when you wrote `var = '2000'`, because that string does not produce an error. The error happens when the string is `var = '2,000'`, so you should put that in the question. See [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – zvone May 18 '18 at 05:59
  • I was an idiot!! completely overlooked it. Yes it was supposed to be '2,000' NOT '2000' and I've updated in the question – keerthan kumar May 18 '18 at 15:27

4 Answers4

2
var = '2000'

print(type(int(var)))

Output:

<class 'int'>

Explanation:

Use the int to convert into integer

2

I get these results :

var = '2000'
print(type(var)) # <class 'str'>
myInt = int(var)
print(type(myInt)) # <class 'int'>

So could you try and share all your relevant code please.

cpaludan
  • 96
  • 1
  • 5
2

If your number contains ',' then you should use this.

 > var = '2,000'
 > int(a.replace(',', ''))
 > 2000

else this

 >  var = '2000'
 >  i = int(var)
Sanjit Prasad
  • 398
  • 2
  • 12
2

I think your error message shows you are using "2,000" not "2000" try using str.replace to remove comas or any letters in your strings

 int ("2,000,000".replace("," , ""))
guramarx
  • 25
  • 5