long integers

Steve Holden sholden at holdenweb.com
Mon Apr 1 18:05:14 EST 2002


"Michael Hall" <olc at ninti.com> wrote in message
news:mailman.1017540760.21438.python-list at python.org...
>
> G'day:
>
> I'm using Python 1.5.2 and am having trouble with long integers when I
> pull data out of a MySQL database using MySQLdb. When I retrieve a
> numeric value from a field with an `int' data type, the value has an `L'
> stuck on the end.
>
> In one script, I worked around this by stripping the L off with:
>
> var = numeric_id # ("2L")
> var = var[:-1]
> print var
> >> 2
>
Clearly the value in var isn't coming from a numeric database field, because
if you tried this with a long integer you would be told it is an
unsubscriptable object. What you have is, I suspect, a string.

> In this case, numeric_id was passed through a hidden field in an HTML

HTML form values are *always* passed as strings. The MySQLdb module will
obligingly store such a value in an integer database column, since it's
smart enough to do the conversion (and to complain if the string isn't a
valid integer).

> form. But this doesn't work in another script for some reason, where
> the value is passed straight from a database query. I tried
> converting the data type from number to string, but that doesn't work
> either:
>
> var = result[0] # ("2L")
> var = 'var[:-1]'
> print var
> >> var[:-1]
>
If you had removed the single quotes around the right-hand side of the
expression you would probably have seen the "unsubscriptable value"
exception I mentioned above. As it is you are just setting var to the
eight-character string "var[:-1]", which won't help you.

> So now I'm confused. I don't yet know enough Python to know what to try
> now. Is there some easy way around this problem? Can this be fixed in
> MySQL by changing or modifying the data type, or should I upgrade to a
> later version of Python?

The bottom line is that you should only see this behavior when printing
these values out, because the print statement invokes the __repr__() method
of the objects it is called on to print.  Ordinary string representations of
long integers don't (nowadays) include the trailing "L". Explicit string
conversion is all you need, since repr(str(x)) == str(x):

>>> str(1L)
'1'
>>> repr(1L)
'1L'

Hope this helps. Python database usage is pretty easy, and MySQL is
extremely good value for money (particulary the freeware versions).

regard=s
 Steve








More information about the Python-list mailing list