Deleting non unicode characters python

梦想与她 提交于 2021-01-28 03:41:30

问题


I am trying to return a request but it is giving me an error that there are non-unicode characters in the string. I am filtering them out but then it makes the string in unicode style which crashes the app with a badly formatted response.

Here is what I am trying to do

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)

The troubles is it appends a string that looks like

{'distance': 4.075068111513138, 'location_id': 1368, 'name': u'Stanford University', 'address': u'450 Serra Mall, Stanford, CA 94305'}

when I need the u'string' to just be 'string' like this

{'distance': 4.075068111513138, 'location_id': 1368, 'name': 'Stanford University', 'address': '450 Serra Mall, Stanford, CA 94305'}

if I try using string.encode('ascii','ignore') then I still get

"{'location_id': 1368, 'address': u'450 Serra Mall, Stanford, CA 94305', 'distance': 4.075068111513138, 'name': u'Stanford University'}"

and now I get extra quotations around the json


回答1:


So, I'm going to go out on a limb here and say that your goal here is to ignore the unicode specific characters that you've got. I think it's really difficult to say anything definitive without a better explanation in your question, but if you're looking to get a "plain" string instead of a unicode one I would suggest using the ascii codec for encoding instead of utf-8.

<str>.encode('ascii')

If you want to remove the other characters, the encode function takes an optional second argument allowing you to ignore all characters that the specified codec can't handle:

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


来源:https://stackoverflow.com/questions/28649795/deleting-non-unicode-characters-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!