1

I'm using int(myString), myString = "-1" and I get error:

ValueError: invalid literal for int() with base 10: '"-1"'
2
  • 1
    What's your Python version, 2.7 does int("-1") with no problem. Looks like your number is double quoted. Was able to reproduce it by int('"-1"') Commented Mar 1, 2012 at 13:09
  • Why define the myString after the conversion? Can you post all you code? Commented Mar 1, 2012 at 13:11

5 Answers 5

11

The string contains quotes, i.e.

s = '"-1"'

You need to get rid of the quotes, something like

s = '"-1"'
int(s.replace('"', ''))

should do the trick.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, I'm modifying someones code so it wasn't that easy to notice, in fact I just guessed that there should be "-1" but there wasn't, and I have 1 hour of python programming experience ;)
2

Are you sure that you're string doesent look like "'-1'" and not "-1"

a = "'-1'"
print int(a)
>>> ValueError: invalid literal for int() with base 10: '"-1"'

a = "-1"
print int(a)
>>> -1

Comments

1
In [2]: int(eval('"-1"'))
Out[2]: -1

Comments

1
>>> int("-1")
-1

>>> int('"-1"')

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

>>> '"-1"'.strip('\"')
'-1'

Comments

1

str.strip method accepts characters. You can use it to get rid of surrounding quotes:

>>> int('"-1"'.strip('"'))
-1
>>> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.