I get quite some traffic for the term “invalid literal for int with base 10″. I guess a lot people fumbling around with Python or Django are getting this error message once in a while. This happens when you try to cast a string into an integer and this string does not really contain a “digit”:
Python 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)] on win32
Type “help”, “copyright”, “credits” or “license” for more information.
>>> string = “TestString”
>>>number = int(string)
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
ValueError: invalid literal for int() with base 10: ‘TestString’
>>>string = “1″
>>>number = int(string)
>>>number
1
If you work with the Django framework and get this error while trying to request a web page I would check the parameters. Since every parameter that is getting passed in a request is a string you probably cast them into integers somewhere in your source code. It can be a category id or similar. Now when that category id for whatever reason is empty or does not contain a string that can be cast into an integer, you will get the “invalid literal for int with base 10″ error message.
To avoid this error you should check if the string contains a digit:
Python 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)] on win32
Type “help”, “copyright”, “credits” or “license” for more information.
>>> string = “1″
>>> if string.isdigit():
… number = int(string)
… else:
… print “The variable String contains no digit”
…
>>> number
1
str.isdigit()
Return true if all characters in the string are digits and there is at least one character, false otherwise.
For 8-bit strings, this method is locale-dependent.
More on String operations can be found in the Python documentation.




#1 by Kevin McConnell on February 16th, 2009
Quote
WIth Django, if you have URLs that require integer parameters you can also enforce that in the URL pattern. For example, where you might have something like this:
url(r’^category/(?P.*)$’, show_category)
you could instead do this:
url(r’^category/(?P\d+)$’, show_category)
The ‘\d+’ will ensure that only a sequence of digits will satisfy the pattern.
Cheers,
Kevin
#2 by A.T. on April 18th, 2010
Quote
So, what if I want a non-base 10 int out my char? How would I do that? I’m trying to port a small code from C to Python and it basically takes a binary buffer and does some bit-wise operations on each char in the buffer. It works fine in C. Seemingly correctly translated Python versions gives that ValueError that you are talking about in this article….
Thanks,
A.T.
Pingback: Invalid Literal for int() with base 10: ’11 08:32:31′ « Becoming a Builder.
#3 by Marik on November 28th, 2010
Quote
@Kevin McConnell
what if my url is like url(r’^category/(?P\d+)/buy/$’, show_category)
ha?
#4 by SLT-A77 on November 16th, 2011
Quote
Ciao, davvero interessante, grazie