Convertir datos Unicode a int en python


Estoy recibiendo valores pasados de url como:

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

Luego usándolo como

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)

Imprime : <type 'unicode'>

, Pero sigo recibiendo el type de limit como unicode, lo que genera un error de consulta!! Estoy convirtiendo unicode a int pero ¿por qué no está convirtiendo?? Por favor, ayuda!!!

Author: shx2, 2013-05-10

2 answers

int(limit) devuelve el valor convertido en un entero, y no lo cambia en su lugar cuando llama a la función (que es lo que espera).

Haga esto en su lugar:

limit = int(limit)

O al definir limit:

if 'limit' in user_data :
    limit = int(user_data['limit'])
 46
Author: TerryA,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-26 20:53:48

En python, los enteros y las cadenas son inmutables y son pasados por el valor. No puede pasar una cadena, o un entero, a una función y esperar que el argumento sea modificado.

Así que para convertir la cadena limit="100" a un número, debe hacer

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

Si realmente quieres rodearlo, puedes usar una lista. Las listas son mutables en python; cuando se pasa una lista, se pasa su referencia, no copia. Así que usted podría hacer:

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

Pero no deberías necesitarlo realmente. (tal vez a veces cuando se trabaja con recursiones y la necesidad de pasar algún estado mutable).

 7
Author: Jakub M.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:02:02