Convert Unicode data to int in python

Question:

I am getting values passed from url as :

user_data = {}
if (request.args.get('title')) :
    user_data['title'] =request.args.get('title')
if(request.args.get('limit')) :
    user_data['limit'] =    request.args.get('limit')

Then using it as

if 'limit' in user_data :
    limit = user_data['limit']
conditions['id'] = {'id':1}
int(limit)
print type(limit)
data = db.entry.find(conditions).limit(limit)

It prints : <type 'unicode'>

but i keep getting the type of limit as unicode, which raises an error from query!! I am converting unicode to int but why is it not converting??
Please help!!!

Asked By: Sankalp Mishra

||

Answers:

int(limit) returns the value converted into an integer, and doesn’t change it in place as you call the function (which is what you are expecting it to).

Do this instead:

limit = int(limit)

Or when definiting limit:

if 'limit' in user_data :
    limit = int(user_data['limit'])
Answered By: TerryA

In python, integers and strings are immutable and are passed by value. You cannot pass a string, or integer, to a function and expect the argument to be modified.

So to convert string limit="100" to a number, you need to do

limit = int(limit) # will return new object (integer) and assign to "limit"

If you really want to go around it, you can use a list. Lists are mutable in python; when you pass a list, you pass it’s reference, not copy. So you could do:

def int_in_place(mutable):
    mutable[0] = int(mutable[0])

mutable = ["1000"]
int_in_place(mutable)
# now mutable is a list with a single integer

But you should not need it really. (maybe sometimes when you work with recursions and need to pass some mutable state).

Answered By: Jakub M.
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.