alhcr
alhcr

Reputation: 823

How to convert string with signed integer value to signed integer?

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

ValueError: invalid literal for int() with base 10: '"-1"'

Upvotes: 1

Views: 7316

Answers (5)

warvariuc
warvariuc

Reputation: 59674

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

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

Upvotes: 1

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24163

>>> 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'

Upvotes: 1

avasal
avasal

Reputation: 14872

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

Upvotes: 1

Jonas Bystr&#246;m
Jonas Bystr&#246;m

Reputation: 26189

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.

Upvotes: 11

aweis
aweis

Reputation: 5616

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

Upvotes: 2

Related Questions