删除非unicode字符python

时间:2015-02-21 18:44:09

标签: python django unicode

我正在尝试返回一个请求,但是它给了我一个错误,即字符串中有非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'}

当我需要你的字符串'就像这样'字符串'

{'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周围得到额外的引用

1 个答案:

答案 0 :(得分:1)

所以,我要在这里走出去,说你的目标是忽略你所拥有的unicode特定角色。我认为如果没有在你的问题中做出更好的解释,说出任何确定的内容真的很难,但如果你想要得到一个简单的"字符串而不是unicode我建议使用ascii编解码器进行编码而不是utf-8

<str>.encode('ascii')

如果要删除其他字符,encode函数会使用可选的第二个参数,允许您忽略指定编解码器无法处理的所有字符:

<str>.encode('ascii', 'ignore')