【问题标题】:Deleting non unicode characters python删除非Unicode字符python
【发布时间】: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,那么您不应该使用 Python repr 输出(考虑使用 JSON 编码器)。

标签: python django unicode


【解决方案1】:

所以,我要冒昧地说一下,你的目标是忽略你所拥有的 unicode 特定字符。我认为如果您的问题没有更好的解释,很难说出任何确定的内容,但是如果您希望获得“普通”字符串而不是 unicode 字符串,我建议您使用 ascii 编解码器而不是 @987654322 进行编码@。

<str>.encode('ascii')

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

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

【讨论】:

  • Python 中没有类型转换之类的东西,使用str() 会生成str() 类型的新对象,前提是unicode 字符串可以使用默认编解码器进行编码。使用str() 意味着您依靠unicode_version 可以使用ASCII 编解码器将其编码为字节;您可能想改用显式编解码器。
  • @MartijnPieters 这完全是公平的,抱歉,我想我在看到上面有明确的utf-8 编码之前有点草率地回答了,现在正在修改。
  • @TylerRice 如果没有更全面地了解您正在尝试做什么,仍然很难提供准确的反馈。如果你只是想摆脱u,你仍然可以做str(),但我觉得还有更多的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-30
  • 2019-11-26
  • 2013-09-25
  • 2018-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多