Luigi Tiburzi
Luigi Tiburzi

Reputation: 4325

Invalid literal for int() Python

I got invalid literal for int() in Python but it is really weird because the literal is "1". Of course if I try in IPython int("1") or int(u"1") I have no errors but in my own code the same instruction gives an error.

        try:
            VimsLog().debug("val = %s" % val)
            int(val)
        except Exception, e:
            VimsLog().debug(e)
            VimsLog().debug("I am died")
            return val

Where

e=invalid literal for int(): "1"

For reason of compatibility I'm using Python 2.4

Upvotes: 3

Views: 16879

Answers (2)

Eugen
Eugen

Reputation: 805

I've tried all there upper solutions but it's just not working. Instead, for me it worked:

val = "15.1234"
int(float(str(val)))

result

>>15

Upvotes: 5

Aaron Digulla
Aaron Digulla

Reputation: 328566

repr(val) gives u'"1"'

this means you're not converting 1, you're trying to convert "1" (i.e. the string quote, 1, quote). That's not a valid integer literal.

Strip the quotes:

int(val.strip('"'))

Upvotes: 5

Related Questions