Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 560
Sankalp Mishra Avatar asked May 10 '13 06:05

Sankalp Mishra


People also ask

How will you convert an integer to an Unicode character in Python?

unichr() is named chr() in Python 3 (conversion to a Unicode character).

How do you change a Unicode to a string in Python?

To convert Python Unicode to string, use the unicodedata. normalize() function. The Unicode standard defines various normalization forms of a Unicode string, based on canonical equivalence and compatibility equivalence.

How do you convert string to int in Python?

To convert a string to integer in Python, use the int() function. This function takes two parameters: the initial string and the optional base to represent the data. Use the syntax print(int("STR")) to return the str as an int , or integer.

What does Unicode () do in Python?

Remarks. If encoding and/or errors are given, unicode() will decode the object which can either be an 8-bit string or a character buffer using the codec for encoding. The encoding parameter is a string giving the name of an encoding; if the encoding is not known, LookupError is raised.


2 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']) 
like image 99
TerryA Avatar answered Oct 11 '22 19:10

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

like image 32
Jakub M. Avatar answered Oct 11 '22 17:10

Jakub M.