If you have stored string literals in the database, then short of accessing the database with Python 2, converting to longs and storing them properly, there is no other way save for string parsing.
You can use regular expressions, or simply drop the last character if its L
.
try:
value = int(possible_long)
except ValueError:
if possible_long[-1] == 'L':
value = int(possible_long[:-1]) # this can still raise an exception,
# but we need to raise at this point
# as the value isn't a string repr of float
Normally, you don't need to worry about type conversion. The Python database drivers will make sure that the data returned is of the correct type for the version of Python being used.
You must, however, give the correct representation in the query string to convert values. If you use string concatenation, you will not benefit from this behavior.
When you print
the result of a database call, you are seeing the translated values and are seeing Python types, not the literal value from the database.
They do not simply "copy and paste" the values from the database. In your comment you referred to this question, specifically this piece of code:
{'estimated': '',
'suffix': '',
'typeofread': 'g',
'acct_no': 901001000L,
'counter': 0,
'time_billed': datetime.datetime(2012, 5, 1, 9, 5, 33),
'date_read': datetime.datetime(2012, 3, 13, 23, 19, 45),
'reading': 3018L,
'meter_num': '26174200'}
This is a result of the type conversion that the database drivers do for you. What you are seeing here is the Python data type equivalent, for the values received from the database.
The value 901001000L
is the Python long type, for the data received from the database. You can tell its not a string literal because it is not quoted, unlike '26174200'
which is quoted and thus is a string literal; most likely the database column type for meter_num
is a character or string type.
This example is from Python 2, thus the L
, if you ran the same code against Python 3, you would not see the L
in the result.
To confirm this behavior, access the database with any other client (such as the mysql>
client) and you will see that the value is not stored as nine zero one zero zero one zero zero zero L but rather the native type that the database column represents.