【发布时间】:2015-04-23 08:39:22
【问题描述】:
我正在尝试返回一个请求,但它给了我一个错误,即字符串中有非 unicode 字符。我将它们过滤掉,但随后它以 unicode 样式生成字符串,导致应用程序崩溃,响应格式错误。
这就是我想要做的事情
unfiltered_string = str({'location_id': location.pk, 'name': location.location_name,'address': location.address+', '+location.locality+', '+location.region+' '+location.postcode, 'distance': location.distance.mi, })
filtered_string = str(filter(lambda x: x in string.printable, unfiltered_string)).encode("utf-8")
locations.append(filtered_string)
问题是它附加了一个看起来像
的字符串{'distance': 4.075068111513138, 'location_id': 1368, 'name': u'Stanford University', 'address': u'450 Serra Mall, Stanford, CA 94305'}
当我需要 u'string' 就像这样的 'string' 时
{'distance': 4.075068111513138, 'location_id': 1368, 'name': 'Stanford University', 'address': '450 Serra Mall, Stanford, CA 94305'}
如果我尝试使用string.encode('ascii','ignore'),我仍然会得到
"{'location_id': 1368, 'address': u'450 Serra Mall, Stanford, CA 94305', 'distance': 4.075068111513138, 'name': u'Stanford University'}"
现在我在 json 周围得到了额外的引用
【问题讨论】:
-
请向我们展示您的完整回溯以及产生错误的代码。我确信你所做的对于你所面临的问题是不正确的。
-
“当我需要 u'string' 就像这样的 'string' 时”——为什么?您正在通过
dict.str()生成repr输出,这是Unicode 字符串的有效Python 文字语法。如果您尝试生成某种不是 Python 文字的格式,例如 JavaScript,那么您不应该使用 Pythonrepr输出(考虑使用 JSON 编码器)。