在python中将Unicode数据转换为int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16476484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Unicode data to int in python
提问by Sankalp Mishra
I am getting values passed from url as :
我正在获取从 url 传递的值:
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'>
它打印: <type 'unicode'>
but i keep getting the typeof limitas unicode, which raises an error from query!! I am converting unicode to int but why is it not converting??
Please help!!!
但我不断收到type的limit是unicode,从查询产生一个错误!我正在将 unicode 转换为 int 但为什么不转换?请帮忙!!!
采纳答案by TerryA
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).
int(limit)返回转换为整数的值,并且不会在您调用函数时就地更改它(这是您期望的)。
Do this instead:
改为这样做:
limit = int(limit)
Or when definiting limit:
或者在定义时limit:
if 'limit' in user_data :
limit = int(user_data['limit'])
回答by Jakub M.
In python, integers and strings are immutableand are passed by value. You cannot pass a string, or integer, to a function and expect the argument to be modified.
在 python 中,整数和字符串是不可变的,并且通过 value 传递。您不能将字符串或整数传递给函数并期望修改参数。
So to convert string limit="100"to a number, you need to do
所以要将字符串转换limit="100"为数字,你需要做
limit = int(limit) # will return new object (integer) and assign to "limit"
If you reallywant 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:
如果你真的想绕过它,你可以使用一个列表。列表在 python 中是可变的;当你传递一个列表时,你传递的是它的引用,而不是复制。所以你可以这样做:
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).
但你不应该真的需要它。(也许有时当您使用递归并需要传递一些可变状态时)。

