简体   繁体   中英

Convert Unicode data to int in python

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!!!

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'])

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM