将 Unicode 字符串转换为十进制 - Python 2.7

convert Unicode string to Decimal - Python 2.7

我正在用 webapp2 编写一个 GAE 项目。
我需要将 unicode 字符串转换为十进制值。

我从客户端收到 lat 这样的:

lat = self.request.get('lat')

在调试器中,我可以看到 lat 已收到并且是这样的:u'50.41688620000001' 但任何尝试转换它都失败了。 我正在这样转换:

edit = Decimal(lat)

错误如下:InvalidOperation:十进制的无效文字:''
但是:
当我明确地写

lat = u'50.41688620000001'

而不是

lat = self.request.get('lat')

十进制和浮点数的转换都很好。 可能是什么问题?

编辑: 当我写

lat = self.request.get('lat')
print lat

这在控制台中打印 两行:第一行是空的(有建议但不确定为什么)第二行实际上是 50.41688620000001.

所以当处理 Decimal(lat) 时,它首先取空值。

编辑2: 坐了一段时间后,我意识到了实际的问题。 我调用了这个服务器函数,它转换来自两个 jquery ajax 函数的值。一个确实将 lat 发送到服务器,另一个没有但做了一些其他工作。由于该函数被调用了两次,因此 self.request.get('lat') 也被赋值了两次:一个为空,另一个为预期值 - 一个 Unicode 值。所以在转换和碰撞到空值时,出现了空字符串的错误:InvalidOperation: Invalid literal for Decimal: ''

lat = u'50.41688620000001'

print(float(lat.encode("ascii","ignore")))

def unicodeTofloat(unicode):
    unicode=str(unicode)
    ret=0.0
    integer=unicode[:unicode.find('.')]
    decimal=unicode[unicode.find('.')+1:]
    ii=1
    for i in integer:
        ret += int((10**(len(integer)-ii))*int(i))
        ii+=1
    ii=-1
    for i in decimal:
        i=int(i);
        ret += (i*(10**ii))
        ii-=1
    return ret;

lat = u'50.41688620000001'
print(str(unicodeTofloat(lat)))

lat = u'50.41688620000001'
print(float(str(lat)))

你的错误信息很清楚:

Invalid literal for Decimal: ''
#                            ^^

它告诉您空字符串 ('') 不是 Decimal() 对象的有效文字。您的 lat 值不是导致此问题的原因; 那个值工作正常:

>>> from decimal import Decimal
>>> lat = u'50.41688620000001'
>>> Decimal(lat)
Decimal('50.41688620000001')

webapp2 框架中 self.request.get('lat') 将 return 一个空字符串,如果 lat 参数 不存在 URL 获取参数。见 Request Data:

By default, get() returns the empty string ('') if the requested argument is not in the request.

您可能想防止这种情况发生,或者改为检索合理的默认值:

lat = self.request.get('lat', '0.0')  # provide a default

lat = self.request.get('lat')
if not lat:
    # return an error message, as lat is missing or empty

lat = self.request.get('lat')
if lat:
    # lat is provided, parse it to a Decimal
    lat = Decimal(lat)

为什么不用这个?

edit = Decimal(lat or 0)

如果 "lat" 是假的(一个空字符串,None)它 returns 后面的部分 "or",在这个例子中是 0。所以如果 "lat" 是一个空字符串,"lat or 0" 转换为 0。因此表达式转换为 "Decimal(0)".