我正在尝试返回一个请求,但它给我一个错误,提示字符串中有非 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 的额外引用
请您参考如下方法:
所以,我要冒昧地说一下,您的目标是忽略您拥有的 unicode 特定字符。我认为如果你的问题没有更好的解释就很难说出任何明确的东西,但如果你想获得一个“普通”字符串而不是一个 unicode 字符串,我建议使用 ascii 编解码器编码而不是 utf-8。
<str>.encode('ascii')
如果您想删除其他字符,encode 函数采用可选的第二个参数,允许您忽略指定编解码器无法处理的所有字符:
<str>.encode('ascii', 'ignore')
